Beispiel #1
0
// launch a process and wait for it to exit, replying to the connection
// with its status
func launchProcess(conn *connection, id int, file string, argv []string, asroot bool) {
	var err error

	// run the command
	cmd := exec.Command(file)
	cmd.Args = argv
	if asroot == false {
		syscall.Setuid(1000)
	}
	err = cmd.Start()
	if asroot == false {
		syscall.Setuid(0)
	}

	// immediate error
	if err != nil {
		conn.send("processEnded", map[string]interface{}{
			"id":    id,
			"pid":   cmd.Process.Pid,
			"error": true,
		})
		return
	}

	// wait for the process to exit
	cmd.Wait()

	// send a successful "process ran" response
	conn.send("processEnded", map[string]interface{}{
		"id":    id,
		"pid":   cmd.Process.Pid,
		"error": false,
	})
}
Beispiel #2
0
// TestHostKeyFile tests that reading and writing the wrong host key file fails
func TestWrongHostKeyFile(t *testing.T) {
	// Non-existent host key file should fail
	f := NewHostKeyFile(wrongHostFile)
	_, err := f.GetHostKeys()
	if err == nil {
		t.Fatal("should fail to read wrong host file")
	}
	if _, ok := err.(*os.PathError); !ok {
		t.Fatalf("should fail to read wrong host file due to file miss, but got %v", err)
	}

	// Create a host key file we do not have permission to read
	os.OpenFile(wrongHostFile, os.O_CREATE, 0000)
	defer os.Remove(wrongHostFile)
	// If run as root, drop privileges temporarily
	if id := syscall.Geteuid(); id == 0 {
		if err := syscall.Setuid(12345); err != nil {
			t.Fatalf("error setting uid: %v", err)
		}
		defer syscall.Setuid(id)
	}
	err = f.PutHostKey("", nil)
	if err == nil {
		t.Fatal("should fail to write wrong host file")
	}
	if !os.IsPermission(err) {
		t.Fatalf("should fail to write wrong host file due to permission denied, but got %v", err)
	}
}
Beispiel #3
0
func chuser(username string) (uid, gid int) {
	usr, err := user.Lookup(username)

	if err != nil {
		fmt.Printf("failed to find user %q: %s", username, err)
	}

	uid, err = strconv.Atoi(usr.Uid)

	if err != nil {
		fmt.Printf("bad user ID %q: %s", usr.Uid, err)
	}

	gid, err = strconv.Atoi(usr.Gid)

	if err != nil {
		fmt.Printf("bad group ID %q: %s", usr.Gid, err)
	}

	if err := syscall.Setgid(gid); err != nil {
		fmt.Printf("setgid(%d): %s", gid, err)
	}

	if err := syscall.Setuid(uid); err != nil {
		fmt.Printf("setuid(%d): %s", uid, err)
	}

	return uid, gid
}
Beispiel #4
0
// Takes care of dropping privileges to the desired user
func changeUser(u string) {
	if u == "" {
		return
	}
	userent, err := utils.UserLookup(u)
	if err != nil {
		log.Fatalf("Unable to find user %v: %v", u, err)
	}

	uid, err := strconv.Atoi(userent.Uid)
	if err != nil {
		log.Fatalf("Invalid uid: %v", userent.Uid)
	}
	gid, err := strconv.Atoi(userent.Gid)
	if err != nil {
		log.Fatalf("Invalid gid: %v", userent.Gid)
	}

	if err := syscall.Setgid(gid); err != nil {
		log.Fatalf("setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		log.Fatalf("setuid failed: %v", err)
	}
}
Beispiel #5
0
func runAsUserName(desiredUserName string) bool {
	// We do not have logging set up yet. We just panic() on error.

	if desiredUserName == "" {
		return false
	}

	currentUser, err := user.Current()
	if err != nil {
		panic(fmt.Sprintf("Can't find current user: %s", err.Error()))
	}

	desiredUser, err := user.Lookup(desiredUserName)
	if err != nil {
		// Not a fatal error, we'll just try the next
		return false
	}

	if currentUser.Uid != desiredUser.Uid {
		numericId, err := strconv.Atoi(desiredUser.Uid)
		if err != nil {
			panic(fmt.Sprintf("Can't interpret [%s] as a numeric user id [following lookup of usernmae %s]", desiredUser.Uid, desiredUserName))
		}
		err = syscall.Setuid(numericId)
		if err != nil {
			panic(fmt.Sprintf("Can't setuid to [%s]: %s", desiredUser.Uid, err.Error()))
		}
	}
	return true
}
Beispiel #6
0
func main() {
	if len(os.Args) < 2 {
		log.Fatalln("Usage: asbox <user> <shell command> [args...]")
	}

	user, args := os.Args[1], os.Args[2:]
	databox, err := isDataboxUser(user)
	if err != nil {
		log.Fatalln("Unable to determine if", user, "is a databox user:", err)
	}

	if !databox {
		log.Fatalln(user, "is not a databox user")
	}

	binary, err := exec.LookPath("su")
	if err != nil {
		log.Fatalln("Unable to find 'su':", err)
	}

	runtime.LockOSThread()
	err = syscall.Setuid(0)
	if err != nil {
		log.Fatalln("Unable to setuid")
	}

	args = append([]string{"su", "-", user, "-c", args[0], "--"}, args[1:]...)
	err = syscall.Exec(binary, args, os.Environ())
	log.Fatalln("Failed to exec:", err)
}
Beispiel #7
0
// SetupUser changes the groups, gid, and uid for the user inside the container
func SetupUser(u string) error {
	uid, gid, suppGids, home, err := user.GetUserGroupSupplementaryHome(u, syscall.Getuid(), syscall.Getgid(), "/")
	if err != nil {
		return fmt.Errorf("get supplementary groups %s", err)
	}

	if err := syscall.Setgroups(suppGids); err != nil {
		return fmt.Errorf("setgroups %s", err)
	}

	if err := syscall.Setgid(gid); err != nil {
		return fmt.Errorf("setgid %s", err)
	}

	if err := syscall.Setuid(uid); err != nil {
		return fmt.Errorf("setuid %s", err)
	}

	// if we didn't get HOME already, set it based on the user's HOME
	if envHome := os.Getenv("HOME"); envHome == "" {
		if err := os.Setenv("HOME", home); err != nil {
			return fmt.Errorf("set HOME %s", err)
		}
	}

	return nil
}
Beispiel #8
0
func DropPrivileges(username string) error {
	userInfo, err := user.Lookup(username)
	if err != nil {
		return err
	}

	uid, err := strconv.Atoi(userInfo.Uid)
	if err != nil {
		return err
	}

	gid, err := strconv.Atoi(userInfo.Gid)
	if err != nil {
		return err
	}

	// TODO: should set secondary groups too
	err = syscall.Setgroups([]int{gid})
	if err != nil {
		return err
	}

	err = syscall.Setgid(gid)
	if err != nil {
		return err
	}

	err = syscall.Setuid(uid)
	if err != nil {
		return err
	}

	return nil
}
Beispiel #9
0
// Takes care of dropping privileges to the desired user
func changeUser(args *DockerInitArgs) error {
	if args.user == "" {
		return nil
	}
	userent, err := utils.UserLookup(args.user)
	if err != nil {
		return fmt.Errorf("Unable to find user %v: %v", args.user, err)
	}

	uid, err := strconv.Atoi(userent.Uid)
	if err != nil {
		return fmt.Errorf("Invalid uid: %v", userent.Uid)
	}
	gid, err := strconv.Atoi(userent.Gid)
	if err != nil {
		return fmt.Errorf("Invalid gid: %v", userent.Gid)
	}

	if err := syscall.Setgid(gid); err != nil {
		return fmt.Errorf("setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		return fmt.Errorf("setuid failed: %v", err)
	}

	return nil
}
Beispiel #10
0
func main() {
	syscall.Setuid(0)
	usr, e := user.Current()
	if e != nil {
		log.Fatal(e)
	}

CHECK:
	if usr.Name != "System Administrator" {
		fmt.Println("Not running as root, relaunching")

		appdir, _ := osext.Executable()
		appdir_len := len(appdir)
		sudo_path := appdir[0:(appdir_len-7)] + "qtox_sudo" //qtox_sudo is a fork of cocoasudo with all of its flags and other features stripped out

		if _, err := os.Stat(sudo_path); os.IsNotExist(err) {
			fmt.Println("Error: No qtox_sudo binary installed, falling back")
			custom_user = usr.Name
			usr.Name = "System Administrator"
			goto CHECK
		}

		relaunch := exec.Command(sudo_path, appdir, usr.Name)
		relaunch.Stdout = os.Stdout
		relaunch.Stderr = os.Stderr
		relaunch.Run()
		return

	} else {

		if len(os.Args) > 1 || custom_user != "" {

			if custom_user == "" {
				custom_user = os.Args[1]
			}

			update_dir := "/Users/" + custom_user + "/Library/Preferences/tox/update/"
			if _, err := os.Stat(update_dir); os.IsNotExist(err) {
				fmt.Println("Error: No update folder, is check for updates enabled?")
				return
			}
			fmt.Println("qTox Updater")

			killqtox := exec.Command("/usr/bin/killall", "qtox")
			_ = killqtox.Run()

			install(update_dir, len(update_dir))

			os.RemoveAll(update_dir)
			fmt.Println("Update metadata wiped, launching qTox")
			launchqtox := exec.Command("/usr/bin/open", "-b", "chat.tox.qtox")
			launchqtox.Run()

		} else {
			fmt.Println("Error: no user passed")
		}

	}
}
Beispiel #11
0
// SetupEnv will create pidfile and possibly change the workdir.
func SetupEnv(cfg *config.Config) error {

	if cfg.System.User != "" {
		// Get the current user
		currentUser, err := user.Current()
		if err != nil {
			return fmt.Errorf("Could not get the current user: %s", err)
		}

		// If the current user is different than the wanted user, try to change it
		if currentUser.Username != cfg.System.User {

			wantedUser, err := user.Lookup(cfg.System.User)
			if err != nil {
				return err
			}

			uid, err := strconv.Atoi(wantedUser.Uid)
			if err != nil {
				return fmt.Errorf("Error converting UID [%s] to int: %s", wantedUser.Uid, err)
			}

			gid, err := strconv.Atoi(wantedUser.Gid)
			if err != nil {
				return fmt.Errorf("Error converting GID [%s] to int: %s", wantedUser.Gid, err)
			}

			if err = syscall.Setgid(gid); err != nil {
				return fmt.Errorf("Setting group id: %s", err)
			}

			if err = syscall.Setuid(uid); err != nil {
				return fmt.Errorf("Setting user id: %s", err)
			}
		}
	}

	if cfg.System.Workdir != "" {
		if err := os.Chdir(cfg.System.Workdir); err != nil {
			return fmt.Errorf("Could not chdir to '%s': %s", cfg.System.Workdir, err)
		}
	}

	pFile, err := os.Create(cfg.System.Pidfile)

	if err != nil {
		return err
	}
	defer pFile.Close()

	_, err = pFile.WriteString(fmt.Sprintf("%d", os.Getpid()))

	if err != nil {
		return err
	}

	return nil
}
Beispiel #12
0
func DropPrivileges(uid int, gid int) (error, bool) {
	if err := syscall.Setuid(uid); err != nil {
		return err, false
	}
	if err := syscall.Setgid(gid); err != nil {
		return err, false
	}
	return nil, true
}
Beispiel #13
0
// SetRuntimeUser sets user on what to run as
func SetRuntimeUser(username string) (err error) {
	log.Printf("Setting uid %s", username)
	ustruct, err := user.LookupId(username)
	if err != nil {
		return
	}
	euid, _ := strconv.Atoi(ustruct.Uid)
	syscall.Setuid(euid)
	return
}
func main() {
	err := syscall.Setuid(0)
	if err != nil {
		log.Fatal(err)
	}
	cmd := exec.Command("/usr/local/sbin/restart_icinga")
	output, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(output))
}
Beispiel #15
0
// InitProcess create pid file, set working dir, setgid and setuid.
func InitProcess() error {
	// setuid and setgid
	ug := strings.SplitN(Conf.User, " ", 2)
	usr := defaultUser
	grp := defaultGroup
	if len(ug) == 0 {
		// default user and group (nobody)
	} else if len(ug) == 1 {
		usr = ug[0]
		grp = ""
	} else if len(ug) == 2 {
		usr = ug[0]
		grp = ug[1]
	}
	uid := 0
	gid := 0
	ui, err := user.Lookup(usr)
	if err != nil {
		Log.Error("user.Lookup(\"%s\") error(%v)", err)
		return err
	}
	uid, _ = strconv.Atoi(ui.Uid)
	// group no set
	if grp == "" {
		Log.Debug("no set group")
		gid, _ = strconv.Atoi(ui.Gid)
	} else {
		// use user's group instread
		// TODO LookupGroup
		gid, _ = strconv.Atoi(ui.Gid)
	}
	Log.Debug("set user: %v", ui)
	if err := syscall.Setuid(uid); err != nil {
		Log.Error("syscall.Setuid(%d) error(%v)", uid, err)
		return err
	}
	//if err := syscall.Setgid(gid); err != nil {
	//	Log.Error("syscall.Setgid(%d) failed (%s)", gid, err.Error())
	//	return err
	//}
	// change working dir
	Log.Debug("set gid: %d", gid)
	if err := os.Chdir(Conf.Dir); err != nil {
		Log.Error("os.Chdir(\"%s\") error(%v)", "", err)
		return err
	}
	// create pid file
	if err := ioutil.WriteFile(Conf.PidFile, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0644); err != nil {
		Log.Error("ioutil.WriteFile(\"%s\") error(%v)", "", err)
		return err
	}
	return nil
}
Beispiel #16
0
func setuid(u string, g string) (err error) {

	if len(u) <= 0 {
		return
	}

	uid := -1
	gid := -1

	for {
		userent, err := user.Lookup(u)
		if err != nil {
			if userent, err = user.LookupId(u); err != nil {
				log.Println("Unable to find user", u, err)
				break
			}
		}

		uid, err = strconv.Atoi(userent.Uid)
		if err != nil {
			log.Println("Invalid uid:", userent.Uid)
		}
		gid, err = strconv.Atoi(userent.Gid)
		if err != nil {
			log.Println("Invalid gid:", userent.Gid)
		}
		break
	}

	if uid < 0 {
		uid, err = strconv.Atoi(u)
		if err != nil {
			log.Println("Invalid uid:", u, err)
			return
		}
	}

	if gid < 0 {
		gid, err = strconv.Atoi(g)
		if err != nil {
			log.Println("Invalid gid:", g, err)
			return
		}
	}

	if err = syscall.Setgid(gid); err != nil {
		log.Println("setgid failed: ", err)
	}
	if err = syscall.Setuid(uid); err != nil {
		log.Println("setuid failed: ", err)
	}
	return
}
Beispiel #17
0
func (s *internalService) DropPrivileges(arg *struct{ R internalDropArg }, result *struct{ R internalDropResult }) error {
	if rv := syscall.Setgid(arg.R.Gid); rv != nil {
		result.R.SetgidErrno = uintptr(rv.(syscall.Errno))
	} else {
		result.R.GidDropped = true
	}
	if rv := syscall.Setuid(arg.R.Uid); rv != nil {
		result.R.SetuidErrno = uintptr(rv.(syscall.Errno))
	} else {
		result.R.UidDropped = true
	}
	return nil
}
Beispiel #18
0
func AttachFiles(containerId, fromFile, toDir, rootDir, perm, uid, gid string) error {
	if containerId == "" {
		return fmt.Errorf("Please make sure the arguments are not NULL!\n")
	}
	permInt, err := strconv.Atoi(perm)
	if err != nil {
		return err
	}
	// It just need the block device without copying any files
	// FIXME whether we need to return an error if the target directory is null
	if toDir == "" {
		return nil
	}
	// Make a new file with the given premission and wirte the source file content in it
	if _, err := os.Stat(fromFile); err != nil && os.IsNotExist(err) {
		return err
	}
	buf, err := ioutil.ReadFile(fromFile)
	if err != nil {
		return err
	}
	targetDir := path.Join(rootDir, containerId, "rootfs", toDir)
	_, err = os.Stat(targetDir)
	targetFile := targetDir
	if err != nil && os.IsNotExist(err) {
		// we need to create a target directory with given premission
		if err := os.MkdirAll(targetDir, os.FileMode(permInt)); err != nil {
			return err
		}
		targetFile = targetDir + "/" + filepath.Base(fromFile)
	} else {
		targetFile = targetDir + "/" + filepath.Base(fromFile)
	}
	err = ioutil.WriteFile(targetFile, buf, os.FileMode(permInt))
	if err != nil {
		return err
	}
	user_id, _ := strconv.Atoi(uid)
	err = syscall.Setuid(user_id)
	if err != nil {
		return err
	}
	group_id, _ := strconv.Atoi(gid)
	err = syscall.Setgid(group_id)
	if err != nil {
		return err
	}

	return nil
}
Beispiel #19
0
func MaybeBecomeChildProcess() {
	lrs := os.Getenv("_RUNSIT_LAUNCH_INFO")
	if lrs == "" {
		return
	}
	defer os.Exit(2) // should never make it this far, though

	lr := new(LaunchRequest)
	d := gob.NewDecoder(base64.NewDecoder(base64.StdEncoding, strings.NewReader(lrs)))
	err := d.Decode(lr)
	if err != nil {
		log.Fatalf("Failed to decode LaunchRequest in child: %v", err)
	}
	if lr.NumFiles != 0 {
		var lim syscall.Rlimit
		if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
			log.Fatalf("failed to get NOFILE rlimit: %v", err)
		}
		noFile := rlim_t(lr.NumFiles)
		lim.Cur = noFile
		lim.Max = noFile
		if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
			log.Fatalf("failed to set NOFILE rlimit: %v", err)
		}
	}
	if lr.Gid != 0 {
		if err := syscall.Setgid(lr.Gid); err != nil {
			log.Fatalf("failed to Setgid(%d): %v", lr.Gid, err)
		}
	}
	if len(lr.Gids) != 0 {
		if err := syscall.Setgroups(lr.Gids); err != nil {
			log.Printf("setgroups: %v", err)
		}
	}
	if lr.Uid != 0 {
		if err := syscall.Setuid(lr.Uid); err != nil {
			log.Fatalf("failed to Setuid(%d): %v", lr.Uid, err)
		}
	}
	if lr.Path != "" {
		err = os.Chdir(lr.Dir)
		if err != nil {
			log.Fatalf("failed to chdir to %q: %v", lr.Dir, err)
		}
	}
	err = syscall.Exec(lr.Path, lr.Argv, lr.Env)
	log.Fatalf("failed to exec %q: %v", lr.Path, err)
}
Beispiel #20
0
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)
	}
}
Beispiel #21
0
// Init create pid file, set working dir, setgid and setuid.
func Init(userGroup, dir, pidFile string) error {
	// change working dir
	if err := os.Chdir(dir); err != nil {
		return err
	}
	// create pid file
	if err := ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0644); err != nil {
		return err
	}
	// setuid and setgid
	ug := strings.SplitN(userGroup, " ", 2)
	usr := defaultUser
	grp := defaultGroup
	if len(ug) == 0 {
		// default user and group (nobody)
	} else if len(ug) == 1 {
		usr = ug[0]
		grp = ""
	} else if len(ug) == 2 {
		usr = ug[0]
		grp = ug[1]
	}
	uid := 0
	gid := 0
	ui, err := user.Lookup(usr)
	if err != nil {
		return err
	}
	uid, _ = strconv.Atoi(ui.Uid)
	// group no set
	if grp == "" {
		gid, _ = strconv.Atoi(ui.Gid)
	} else {
		// use user's group instread
		// TODO LookupGroup
		gid, _ = strconv.Atoi(ui.Gid)
	}
	if err := syscall.Setgid(gid); err != nil {
		return err
	}
	if err := syscall.Setuid(uid); err != nil {
		return err
	}
	return nil
}
Beispiel #22
0
func changeUser(name string) error {
	user, err := user.Lookup(name)
	if err != nil {
		return err
	}
	uid, err := strconv.Atoi(user.Uid)
	if err != nil {
		return err
	}
	gid, err := strconv.Atoi(user.Gid)
	if err = syscall.Setgroups([]int{gid}); err != nil {
		return err
	}
	if err = syscall.Setuid(uid); err != nil {
		return err
	}
	return nil
}
Beispiel #23
0
func main() {
	var Hostname, User, DatabaseFile, VoicemailDirectory, HttpPort, SmtpPort string
	var Limit int

	flag.StringVar(&Hostname, "host", "localhost", "Hostname or IP to bind to")
	flag.StringVar(&User, "user", "nobody", "User to drop to after binding")
	flag.StringVar(&DatabaseFile, "database", "./voicemail.sqlite", "Database file location")
	flag.StringVar(&VoicemailDirectory, "voicemail", "./mp3/", "Voicemail storage directory")
	flag.StringVar(&HttpPort, "http-port", "8080", "Port for the HTTP service")
	flag.StringVar(&SmtpPort, "smtp-port", "2500", "Port for the SMTP service")
	flag.IntVar(&Limit, "limit", -1, "Only display this many voicemails in the web interface")

	flag.Parse()

	smtpListener, err := net.Listen("tcp", Hostname+":"+SmtpPort)
	if err != nil {
		logger.Panic(err)
	}

	httpListener, err := net.Listen("tcp", Hostname+":"+HttpPort)
	if err != nil {
		logger.Panic(err)
	}

	u, err := user.Lookup(User)
	if err != nil {
		logger.Panic(err)
	}

	uid, _ := strconv.Atoi(u.Uid)
	gid, _ := strconv.Atoi(u.Gid)

	if err = syscall.Setgid(gid); err != nil {
		logger.Panic(err)
	}
	if err = syscall.Setuid(uid); err != nil {
		logger.Panic(err)
	}

	db := model.OpenDatabase(DatabaseFile, VoicemailDirectory)

	go mail.Serve(smtpListener, db)
	web.Serve(httpListener, db, VoicemailDirectory, Limit)
}
Beispiel #24
0
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))
	}
}
Beispiel #25
0
func (t *pty) fork(file string, args, env []string, cwd string, cols, rows, uid, gid int) error {
	var winp = new(C.struct_winsize)
	winp.ws_col = C.ushort(cols)
	winp.ws_row = C.ushort(rows)
	winp.ws_xpixel = 0
	winp.ws_ypixel = 0

	//fork the pty
	var master C.int = -1
	var name []C.char = make([]C.char, 40)
	var pid C.int = C.GoForkpty(&master, &name[0], winp)

	t.fd = int(master)
	t.pid = int(pid)
	t.pty = C.GoString(&name[0])

	switch t.pid {
	case -1:
		return errors.New("forkpty(3) failed")
	case 0:
		if cwd != "" {
			if err := syscall.Chdir(cwd); err != nil {
				panic("chdir failed")
			}
		}

		if uid != -1 && gid != -1 {
			if err := syscall.Setgid(gid); err != nil {
				panic("setgid failed")
			}

			if err := syscall.Setuid(uid); err != nil {
				panic("setuid failed")
			}
		}

		syscall.Exec(file, args, env)
		panic("exec failed")
	}

	return nil
}
Beispiel #26
0
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)
}
Beispiel #27
0
// SetupUser changes the groups, gid, and uid for the user inside the container
func SetupUser(u string) error {
	uid, gid, suppGids, err := user.GetUserGroupSupplementary(u, syscall.Getuid(), syscall.Getgid())
	if err != nil {
		return fmt.Errorf("get supplementary groups %s", err)
	}

	if err := syscall.Setgroups(suppGids); err != nil {
		return fmt.Errorf("setgroups %s", err)
	}

	if err := syscall.Setgid(gid); err != nil {
		return fmt.Errorf("setgid %s", err)
	}

	if err := syscall.Setuid(uid); err != nil {
		return fmt.Errorf("setuid %s", err)
	}

	return nil
}
Beispiel #28
0
func main() {
	var e error
	u := new(user.User)
	u, e = user.Lookup(from_user)
	if e != nil {
		os.Exit(1)
	}

	uid, e := strconv.Atoi(u.Uid)
	if e != nil {
		os.Exit(1)
	}

	if os.Getuid() != uid {
		os.Exit(1)
	}

	// doesn't work cause syscall.Sockaddr type
	// can't be used in any way.
	//syscall.Getsockaddr(fd)
	e = syscall.Dup2(fd, syscall.Stdin)
	if e != nil {
		os.Exit(1)
	}
	e = syscall.Dup2(fd, syscall.Stdout)
	if e != nil {
		os.Exit(1)
	}
	e = syscall.Dup2(fd, syscall.Stderr)
	if e != nil {
		os.Exit(1)
	}
	e = syscall.Close(fd)
	if e != nil {
		os.Exit(1)
	}

	syscall.Setuid(0)
	_ = syscall.Exec("/usr/sbin/sshd", []string{"sshd", "-i"}, []string{})
	os.Exit(1)
}
Beispiel #29
0
// Takes care of dropping privileges to the desired user
func changeUser(args *execdriver.InitArgs) error {
	uid, gid, suppGids, err := user.GetUserGroupSupplementary(
		args.User,
		syscall.Getuid(), syscall.Getgid(),
	)
	if err != nil {
		return err
	}

	if err := syscall.Setgroups(suppGids); err != nil {
		return fmt.Errorf("Setgroups failed: %v", err)
	}
	if err := syscall.Setgid(gid); err != nil {
		return fmt.Errorf("Setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		return fmt.Errorf("Setuid failed: %v", err)
	}

	return nil
}
Beispiel #30
0
func main() {
	var config *string = flag.String("config", "", "Location of configuration file.")
	var def *bool = flag.Bool("default", false, "Enable to create a default config file")
	var daemonize *bool = flag.Bool("daemon", false, "Run in daemon mode")
	flag.Parse()
	if *def {
		bot.CreateDefaultConfig()
		return
	}
	if *daemonize {
		cbotU, err := user.Lookup("cbot")
		if err != nil {
			Printf("ERROR, No user cbot found, maybe you forgot to create it?")
			return
		}
		cbotuid, _ := strconv.Atoi(cbotU.Uid)
		syscall.Setuid(cbotuid) // drop root
	}
	ircbot := bot.NewBot(bot.ReadJSONConfig(*config))

	runWrapper(ircbot)
}