func init() { reexec.Register("chrootwrite", func() { var rootfs, path string var uid, gid int flag.StringVar(&rootfs, "rootfs", "", "rootfs") flag.StringVar(&path, "path", "", "path") flag.IntVar(&uid, "uid", 0, "uid") flag.IntVar(&gid, "gid", 0, "gid") flag.Parse() if err := syscall.Chroot(rootfs); err != nil { panic(err) } if err := os.Chdir("/"); err != nil { panic(err) } var contents bytes.Buffer if _, err := io.Copy(&contents, os.Stdin); err != nil { panic(err) } w := RootfsWriter{} if err := w.writeFile(lager.NewLogger("chroot-write"), path, contents.Bytes(), rootfs, uid, gid); err != nil { panic(err) } }) }
func main() { flag.Parse() log.SetDebug(debug) diag.SetDebug(debug) if !debug { diag.SetOutput(ioutil.Discard) } root, err := getRootDir(podPid) if err != nil { log.FatalE("Failed to get pod root", err) } if err := os.Chdir(root); err != nil { log.FatalE("Failed to change to new root", err) } if err := syscall.Chroot(root); err != nil { log.FatalE("Failed to chroot", err) } diag.Println("PID:", podPid) diag.Println("APP:", appName) diag.Println("ARGS:", flag.Args()) if err := execArgs(); err != nil { log.PrintE("exec failed", err) } os.Exit(254) }
func prepare() { var rootfsPath = flag.String("rootfsPath", "", "rootfs path to chroot into") var uid = flag.Int("uid", 0, "uid to create directories as") var gid = flag.Int("gid", 0, "gid to create directories as") var perm = flag.Int("perm", 0755, "Mode to create the directory with") var recreate = flag.Bool("recreate", false, "whether to delete the directory before (re-)creating it") flag.Parse() runtime.LockOSThread() if err := syscall.Chroot(*rootfsPath); err != nil { panic(err) } if err := os.Chdir("/"); err != nil { panic(err) } for _, path := range flag.Args() { path, err := filepath.Abs(path) if err != nil { panic(err) } if *recreate { rmdir(path) } mkdir(path, *uid, *gid, os.FileMode(*perm)) } }
func main() { var root, cmd string var opts []string if len(os.Args) < 3 { panic("not enough arguments\n") } root = os.Args[1] cmd = os.Args[2] if len(os.Args) > 3 { opts = os.Args[3:len(os.Args)] } rs, err := os.Stat(root) if err != nil { if os.IsNotExist(err) { panic(fmt.Sprintf("'%s' does not exist, cannot chroot there!", root)) } else { panic(fmt.Sprintf("Could not stat '%s': %s", root, err)) } } else { if !rs.Mode().IsDir() { panic(fmt.Sprintf("'%s' is not a directory, cannot chroot there!", root)) } } fmt.Printf("root: %s, cmd: %s, opts: %s\n", root, cmd, opts) err = os.Chdir(root) if err != nil { panic(fmt.Sprintf("chdir failed: %s", err)) } err = syscall.Chroot(root) if err != nil { panic(fmt.Sprintf("chroot failed: %s", err)) } // we're going to exec right away in the child, CLONE_VFORK will block the // parent from being scheduled until the child starts up, see clone(2) pid, err := lnxns.NsFork(lnxns.CLONE_VFORK) if err == syscall.EINVAL { panic("OS returned EINVAL. Make sure your kernel configuration includes all CONFIG_*_NS options.") } else if err != nil { panic(fmt.Sprintf("lnxns.NsFork() failed: %s", err)) } if pid != 0 { proc, _ := os.FindProcess(pid) proc.Wait() } else { err = syscall.Exec(cmd, opts, os.Environ()) if err != nil { panic(fmt.Sprintf("exec failed: %s", err)) } panic("impossible") } }
func switchRoot(rootfs, subdir string, rmUsr bool) error { if err := syscall.Unmount(config.OEM, 0); err != nil { log.Debugf("Not umounting OEM: %v", err) } if subdir != "" { fullRootfs := path.Join(rootfs, subdir) if _, err := os.Stat(fullRootfs); os.IsNotExist(err) { if err := os.MkdirAll(fullRootfs, 0755); err != nil { log.Errorf("Failed to create directory %s: %v", fullRootfs, err) return err } } log.Debugf("Bind mounting mount %s to %s", fullRootfs, rootfs) if err := syscall.Mount(fullRootfs, rootfs, "", syscall.MS_BIND, ""); err != nil { log.Errorf("Failed to bind mount subdir for %s: %v", fullRootfs, err) return err } } for _, i := range []string{"/dev", "/sys", "/proc", "/run"} { log.Debugf("Moving mount %s to %s", i, path.Join(rootfs, i)) if err := os.MkdirAll(path.Join(rootfs, i), 0755); err != nil { return err } if err := syscall.Mount(i, path.Join(rootfs, i), "", syscall.MS_MOVE, ""); err != nil { return err } } if err := copyMoveRoot(rootfs, rmUsr); err != nil { return err } log.Debugf("chdir %s", rootfs) if err := syscall.Chdir(rootfs); err != nil { return err } log.Debugf("mount MS_MOVE %s", rootfs) if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil { return err } log.Debug("chroot .") if err := syscall.Chroot("."); err != nil { return err } log.Debug("chdir /") if err := syscall.Chdir("/"); err != nil { return err } log.Debugf("Successfully moved to new root at %s", path.Join(rootfs, subdir)) os.Unsetenv("DOCKER_RAMDISK") return nil }
func (d *Context) child() (err error) { if initialized { return os.ErrInvalid } initialized = true decoder := json.NewDecoder(os.Stdin) if err = decoder.Decode(d); err != nil { return } if err = syscall.Close(0); err != nil { return } if err = syscall.Dup2(3, 0); err != nil { return } if len(d.PidFileName) > 0 { d.pidFile = NewLockFile(os.NewFile(4, d.PidFileName)) if err = d.pidFile.WritePid(); err != nil { return } } if d.Umask != 0 { syscall.Umask(int(d.Umask)) } if len(d.Chroot) > 0 { err = syscall.Chroot(d.Chroot) } return }
func main() { documentRoot := flag.String("d", "", "Document Root (default: none)") portNumber := flag.String("p", "80", "Port number used by AMS for listening connections") flag.Parse() if *documentRoot == "" { fmt.Printf("Please specify the document root for the web server with -d <document root>") return } mp4.Debug(false) err := syscall.Chroot(*documentRoot) if err != nil { fmt.Printf("Please run Afrostream Media Server as root, cannot chroot the document root directory for security: %v", err) return } listenPort := ":" + *portNumber log.Printf(" [*] Running Afrostream Media Server on %s, To exit press CTRL+C", listenPort) http.HandleFunc("/", httpRootServer) http.ListenAndServe(listenPort, nil) return }
func runChroot(cmd *cobra.Command, args []string) { runtime.LockOSThread() err := syscall.Chroot(flagChroot) if err != nil { errAndExit("couldn't chroot: %v", err) } err = os.Chdir("/") if err != nil { errAndExit("couldn't cd: %v", err) } if flagWorkingDir != "" { err = os.Chdir(flagWorkingDir) if err != nil { errAndExit("couldn't cd: %v", err) } } execCmd := exec.Command(flagCmd, flagArgs...) execCmd.Env = flagEnv execCmd.Stdin = os.Stdin execCmd.Stdout = os.Stdout execCmd.Stderr = os.Stderr err = execCmd.Run() if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { code := exitErr.Sys().(syscall.WaitStatus).ExitStatus() os.Exit(code) } errAndExit("%v", err) } }
func main() { flag.Usage = usage flag.Parse() if flag.NArg() < 1 { usage() } args := flag.Args() ck(syscall.Chroot(args[0])) ck(syscall.Chdir("/")) var cmd *exec.Cmd if len(args) == 1 { shell := os.Getenv("SHELL") if shell == "" { shell = "/bin/sh" } cmd = exec.Command(shell, "-i") } else { cmd = exec.Command(args[1], args[2:]...) } cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout ck(cmd.Run()) }
func realChroot(path string) error { if err := syscall.Chroot(path); err != nil { return fmt.Errorf("Error after fallback to chroot: %v", err) } if err := syscall.Chdir("/"); err != nil { return fmt.Errorf("Error changing to new root after chroot: %v", err) } return nil }
func msMoveRoot(rootfs string) error { if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil { return err } if err := syscall.Chroot("."); err != nil { return err } return syscall.Chdir("/") }
// Chroot runs a command with a changed root. func Chroot(wd string, cmd *exec.Cmd) error { err := syscall.Chroot(wd) if err != nil { return fmt.Errorf("couldn't chroot to directory %s: %+v", wd, err) } if err := cmd.Run(); err != nil { return fmt.Errorf("error while running command %+v: %+v", cmd, err) } return nil }
func containerChroot(fsPath string) error { err := syscall.Mount(fsPath, "/", "", syscall.MS_MOVE, "") if err != nil { return err } err = syscall.Chroot(".") if err != nil { return err } return syscall.Chdir("/") }
func MsMoveRoot(rootfs string) error { if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil { return fmt.Errorf("mount move %s into / %s", rootfs, err) } if err := syscall.Chroot("."); err != nil { return fmt.Errorf("chroot . %s", err) } return syscall.Chdir("/") }
// EnterChroot changes the current directory to the path specified, // and then calls chroot(2) with the same path. This must be called // while the process has CAP_SYS_CHROOT. func EnterChroot(path string) (err error) { if err = syscall.Chdir(path); err != nil { return } if err = syscall.Chroot(path); err != nil { return } if err = syscall.Chdir("/"); err != nil { return } return }
// Because this function is executed by multicall in a different process, it is not possible to use errwrap to return errors func extractTarCommand() error { if len(os.Args) != 5 { return fmt.Errorf("incorrect number of arguments. Usage: %s DIR {true|false} uidShift uidCount", multicallName) } if !sys.HasChrootCapability() { return fmt.Errorf("chroot capability not available.") } dir := os.Args[1] if !filepath.IsAbs(dir) { return fmt.Errorf("dir %s must be an absolute path", dir) } overwrite, err := strconv.ParseBool(os.Args[2]) if err != nil { return fmt.Errorf("error parsing overwrite argument: %v", err) } us, err := strconv.ParseUint(os.Args[3], 10, 32) if err != nil { return fmt.Errorf("error parsing uidShift argument: %v", err) } uc, err := strconv.ParseUint(os.Args[4], 10, 32) if err != nil { return fmt.Errorf("error parsing uidCount argument: %v", err) } uidRange := &user.UidRange{Shift: uint32(us), Count: uint32(uc)} if err := syscall.Chroot(dir); err != nil { return fmt.Errorf("failed to chroot in %s: %v", dir, err) } if err := syscall.Chdir("/"); err != nil { return fmt.Errorf("failed to chdir: %v", err) } fileMapFile := os.NewFile(uintptr(fileMapFdNum), "fileMap") fileMap := map[string]struct{}{} if err := json.NewDecoder(fileMapFile).Decode(&fileMap); err != nil { return fmt.Errorf("error decoding fileMap: %v", err) } editor, err := NewUidShiftingFilePermEditor(uidRange) if err != nil { return fmt.Errorf("error determining current user: %v", err) } if err := ExtractTarInsecure(tar.NewReader(os.Stdin), "/", overwrite, fileMap, editor); err != nil { return fmt.Errorf("error extracting tar: %v", err) } // flush remaining bytes io.Copy(ioutil.Discard, os.Stdin) return nil }
// Chroots into a directory. The package keeps track of the resultant chroot // path, even after multiple successive chroot operations. The anchor is // updated if the operation is successful. func Chroot(path string) error { if !filepath.IsAbs(path) { return fmt.Errorf("chroot path must be absolute: %v", path) } err := syscall.Chroot(path) if err != nil { return err } anchor = filepath.Join(anchor, path[1:]) return nil }
func (exer *Executor) execute() (err error) { path, err := exec.LookPath(exer.name) if err != nil { return fmt.Errorf("Executable not found: %s", err) } exer.path = path env := os.Environ() cwd, err := os.Getwd() if err != nil { return fmt.Errorf("getcwd() failed: %s", err) } if exer.chroot != "" { if err = exer.MkJail(); err != nil { return } if err = os.Chdir(exer.chroot); err != nil { return fmt.Errorf(`Unable to chdir("/"): %s`, err) } if err = syscall.Chroot("."); err != nil { return } } err = syscallx.Setgid(exer.id) if err != nil { return fmt.Errorf("Unable to setgid(), aborting: %s", err) } err = syscallx.Setuid(exer.id) if err != nil { return fmt.Errorf("Unable to setuid(), aborting: %s", err) } if exer.chroot == "" { err = os.Chdir(cwd) if err != nil { err = os.Chdir("/") if err != nil { return fmt.Errorf(`Unable to chdir("/"): %s`, err) } } } err = syscall.Exec(exer.path, append([]string{exer.name}, exer.args...), env) if err != nil { return fmt.Errorf("Not able to execute: %s", err) } return }
func main() { cwd1 := make([]byte, BUF_SZ) fmt.Print("This is where I am now: ") if _, err := syscall.Getcwd(cwd1); err != nil { log.Fatal("Error: syscall.Getcwd(2): ", err) } fmt.Println(string(cwd1)) fmt.Println("chroot(2)ing back to /home/christos") // Commented out doesn't work for some reason. TODO: Why not? //cwd_s := string(cwd[:]) //if err := syscall.Chroot(cwd_s); err != nil { if err := syscall.Chroot("/home/christos"); err != nil { log.Fatal("Error: syscall.Chroot(2): ", err) } fmt.Print("This is where I am now: ") cwd2 := make([]byte, BUF_SZ) if _, err := syscall.Getcwd(cwd2); err != nil { log.Fatal("Error: syscall.Getcwd(2): ", err) } fmt.Println(string(cwd2)) fmt.Println("chdir(2)ing to parent") if err := syscall.Chdir(".."); err != nil { log.Fatal("Error: syscall.Chdir(2): ", err) } fmt.Print("This is where I am now: ") cwd3 := make([]byte, BUF_SZ) if _, err := syscall.Getcwd(cwd3); err != nil { log.Fatal("Error: syscall.Getcwd(2): ", err) } fmt.Println(string(cwd3)) fmt.Println("Again, chdir(2)ing to parent") if err := syscall.Chdir(".."); err != nil { log.Fatal("Error: syscall.Chdir(2): ", err) } fmt.Print("This is where I am now: ") cwd4 := make([]byte, BUF_SZ) if _, err := syscall.Getcwd(cwd4); err != nil { log.Fatal("Error: syscall.Getcwd(2): ", err) } fmt.Println(string(cwd4)) return }
func child() { fmt.Printf("child %v as %d\n", os.Args[2:], os.Getpid()) cmd := exec.Command(os.Args[2], os.Args[3:]...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr must(syscall.Chroot("/var/docker/")) must(os.Chdir("/")) must(syscall.Mount("proc", "proc", "proc", 0, "")) must(cmd.Run()) }
func (fs *Filesystem) Chroot() error { if fs.chroot { return fmt.Errorf("filesystem is already in chroot()") } fs.log.Debug("chroot to %s", fs.Root()) if err := syscall.Chroot(fs.Root()); err != nil { return fmt.Errorf("chroot to %s failed: %v", fs.Root(), err) } if err := os.Chdir("/"); err != nil { return fmt.Errorf("chdir to / after chroot() failed: %v", err) } fs.chroot = true return nil }
func chrootuid(dir, user string) { pw_filename := "/etc/passwd" pwf, err := os.Open(pw_filename) if err != nil { log.Fatalf("%%Can't open %s: %s", pw_filename, err) } pwr := bufio.NewReader(pwf) for { line, err := pwr.ReadString('\n') if err != nil { log.Fatalf("%%Can't find UID for %s: %s", user, err) } pw_row := strings.SplitN(line, ":", 5) if len(pw_row) != 5 { continue } if pw_row[0] == user { uid, err = strconv.Atoi(pw_row[2]) if err != nil { log.Fatalln("%Wrong UID:", err) } gid, err = strconv.Atoi(pw_row[3]) if err != nil { log.Fatalln("%Wrong GID:", err) } break } } err = syscall.Chroot(dir) if err != nil { log.Fatalln("%Chroot error:", err) } err = syscall.Setgid(gid) if err != nil { log.Fatalln("%Setgid error:", err) } err = syscall.Setuid(uid) if err != nil { log.Fatalln("%Setuid error:", err) } err = os.Chdir("/") if err != nil { log.Fatalln("%Can't cd to '/':", err) } }
func TestE2eNode(t *testing.T) { if *runServicesMode { // If run-services-mode is specified, only run services in current process. services.RunE2EServices() return } if *runKubeletMode { // If run-kubelet-mode is specified, only start kubelet. services.RunKubelet() return } if *systemValidateMode { // If system-validate-mode is specified, only run system validation in current process. if framework.TestContext.NodeConformance { // Chroot to /rootfs to make system validation can check system // as in the root filesystem. // TODO(random-liu): Consider to chroot the whole test process to make writing // test easier. if err := syscall.Chroot(rootfs); err != nil { glog.Exitf("chroot %q failed: %v", rootfs, err) } } if err := system.ValidateDefault(); err != nil { glog.Exitf("system validation failed: %v", err) } return } // If run-services-mode is not specified, run test. rand.Seed(time.Now().UTC().UnixNano()) RegisterFailHandler(Fail) reporters := []Reporter{} reportDir := framework.TestContext.ReportDir if reportDir != "" { // Create the directory if it doesn't already exists if err := os.MkdirAll(reportDir, 0755); err != nil { glog.Errorf("Failed creating report directory: %v", err) } else { // Configure a junit reporter to write to the directory junitFile := fmt.Sprintf("junit_%s%02d.xml", framework.TestContext.ReportPrefix, config.GinkgoConfig.ParallelNode) junitPath := path.Join(reportDir, junitFile) reporters = append(reporters, morereporters.NewJUnitReporter(junitPath)) } } RunSpecsWithDefaultAndCustomReporters(t, "E2eNode Suite", reporters) }
func tryChroot(path string) error { if path == "/" { path = "" } if path == "" { return nil } ensureResolverConfigIsLoaded() err := syscall.Chroot(path) if err != nil { return err } return nil }
func main() { flag.Parse() absPath, err := Abs(*baseDirectory) if err != nil { log.Fatalf("Unable to resolve path %v\n", *baseDirectory) } os.Chdir(absPath) log.Printf("Chrooting to %v\n", absPath) if err := syscall.Chroot(absPath); err != nil { log.Fatalf("Unable to chroot: %v\n", err) } handlerCache = make(map[http.Dir]http.Handler) http.HandleFunc("/", hostDispatcher) http.ListenAndServe(":8080", nil) }
func main() { exedir := flag.String("dir", "/", "directory to chroot to.") uid := flag.Int("uid", 0, "uid to use.") gid := flag.Int("gid", 0, "gid to use.") binary := flag.String("binary", "", "full path of binary.") flag.Parse() if len(flag.Args()) < 2 { log.Fatal("use: chroot DIR COMMAND [ARG ..]") } args := flag.Args()[1:] dir := flag.Arg(0) en := syscall.Chroot(dir) if en != 0 { log.Fatalln("Chroot error:", os.Errno(en)) } en = syscall.Setgid(*gid) if en != 0 { log.Fatalln("Setgid error:", os.Errno(en)) } en = syscall.Setuid(*uid) if en != 0 { log.Fatalln("Setuid error:", os.Errno(en)) } err := os.Chdir(*exedir) if err != nil { log.Fatalln("Can't cd to", *exedir, err) } bin := *binary if bin == "" { bin = args[0] } en = syscall.Exec(bin, args, os.Environ()) if en != 0 { log.Fatalln("Can't exec", args, os.Errno(en)) } }
func main() { // NOTE: Sandbox doesn't work correctly with /more/ than 1 goroutine! runtime.GOMAXPROCS(1) // Open the port, to be used later... log.Printf("Opening port...") l, e := net.Listen("tcp", ":80") if e != nil { log.Fatal(e.Error()) } // Chroot into /jailed os.Chdir("/jailed") e = syscall.Chroot("/jailed") if e != nil { log.Fatal("Failed to chroot: %v", e.Error()) } // Drop group (group must be done first, apparently?) e = syscall.Setgid(9999) if e != nil { log.Fatal("Failed to drop group: %v", e.Error()) } // Drop user e = syscall.Setuid(9999) if e != nil { log.Fatal("Failed to drop user: %v", e.Error()) } // Handle pages http.HandleFunc("/", indexHandler) http.HandleFunc("/nyancat.gif", nyanHandler) http.HandleFunc("/bd8d1dda5442e2888b7633335cd38f39a95db855", badSyscallHandler) // TODO: DELETE ME // Enable seccomp filtering Sandbox() // Begin serving on the previously-opened socket log.Printf("Starting web server.") http.Serve(l, nil) }
func Chroot(call []string) error { e := flagSet.Parse(call[1:]) if e != nil { return e } if flagSet.NArg() < 2 || *helpFlag { println("`chroot` [options] <new root> <command>") flagSet.PrintDefaults() return nil } e = syscall.Chroot(flagSet.Arg(0)) if e != nil { return e } e = syscall.Exec(flagSet.Arg(1), flagSet.Args()[1:], os.Environ()) return e }
func applyLayer() { runtime.LockOSThread() flag.Parse() if err := syscall.Chroot(flag.Arg(0)); err != nil { fatal(err) } if err := syscall.Chdir("/"); err != nil { fatal(err) } tmpDir, err := ioutil.TempDir("/", "temp-docker-extract") if err != nil { fatal(err) } os.Setenv("TMPDIR", tmpDir) if err := archive.ApplyLayer("/", os.Stdin); err != nil { os.RemoveAll(tmpDir) fatal(err) } os.RemoveAll(tmpDir) os.Exit(0) }
func extractTarCommand() error { if len(os.Args) != 3 { return fmt.Errorf("incorrect number of arguments. Usage: %s DIR {true|false}", multicallName) } if !sys.HasChrootCapability() { return fmt.Errorf("chroot capability not available.") } dir := os.Args[1] if !filepath.IsAbs(dir) { return fmt.Errorf("dir %s must be an absolute path", dir) } overwrite, err := strconv.ParseBool(os.Args[2]) if err != nil { return fmt.Errorf("error parsing overwrite argument: %v", err) } if err := syscall.Chroot(dir); err != nil { return fmt.Errorf("failed to chroot in %s: %v", dir, err) } if err := syscall.Chdir("/"); err != nil { return fmt.Errorf("failed to chdir: %v", err) } fileMapFile := os.NewFile(uintptr(fileMapFdNum), "fileMap") fileMap := map[string]struct{}{} if err := json.NewDecoder(fileMapFile).Decode(&fileMap); err != nil { return fmt.Errorf("error decoding fileMap: %v", err) } if err := extractTar(tar.NewReader(os.Stdin), overwrite, fileMap); err != nil { return fmt.Errorf("error extracting tar: %v", err) } // flush remaining bytes io.Copy(ioutil.Discard, os.Stdin) return nil }