Example #1
0
func main() {
	kingpin.Parse()

	u, err := user.Lookup(*cliChownUser)
	if err != nil {
		panic(err)
	}

	g, err := user.Lookup(*cliChownGroup)
	if err != nil {
		panic(err)
	}

	uid, err = strconv.Atoi(u.Uid)
	if err != nil {
		panic(err)
	}

	gid, err = strconv.Atoi(g.Gid)
	if err != nil {
		panic(err)
	}

	// Ensure all folders and files are currently set to the correct permissions.
	filepath.Walk(*cliDir, update)

	// Now we will wait for
	watch(*cliDir)
}
Example #2
0
func fsPosixSetPerms(log *logging.Logger, element *common.JSONFile) common.JSONResult {
	var uid, gid int
	var result common.JSONResult

	uname, err := user.Lookup(element.User)
	if err != nil {
		uname, _ := user.Lookup("nobody")
		uid, _ = strconv.Atoi(uname.Uid)
		gid, _ = strconv.Atoi(uname.Gid)
	} else {
		uid, _ = strconv.Atoi(uname.Uid)
		gid, err = getGroupId(element.Group)
		if err != nil {
			gid, _ = getGroupId("nogroup")
		}
	}

	// TODO: fix possible error if element.Mode is empty
	if err := os.Chmod(element.Name, getPerms(element.Mode)); err != nil {
		log.Debug("Error:", err)
		result = common.JSONResult{Result: "ko", Message: err.Error()}
	} else {
		if err := os.Chown(element.Name, uid, gid); err != nil {
			log.Debug("Error:", err)
			result = common.JSONResult{Result: "ko", Message: err.Error()}
		} else {
			result = common.JSONResult{Result: "ok"}
		}
	}

	return result
}
Example #3
0
func isDataboxUser() bool {
	u, err := user.Lookup(pamUser)
	if err != nil {
		Fatal("Failed to obtain passwd entry for %q", pamUser)
	}
	return u.Gid == fmt.Sprint(databoxGid)
}
Example #4
0
func TestClientChownReadonly(t *testing.T) {
	sftp, cmd := testClient(t, READONLY, NO_DELAY)
	defer cmd.Wait()
	defer sftp.Close()

	usr, err := user.Current()
	if err != nil {
		t.Fatal(err)
	}
	chownto, err := user.Lookup("daemon") // seems common-ish...
	if err != nil {
		t.Fatal(err)
	}

	if usr.Uid != "0" {
		t.Log("must be root to run chown tests")
		t.Skip()
	}
	toUid, err := strconv.Atoi(chownto.Uid)
	if err != nil {
		t.Fatal(err)
	}
	toGid, err := strconv.Atoi(chownto.Gid)
	if err != nil {
		t.Fatal(err)
	}

	f, err := ioutil.TempFile("", "sftptest")
	if err != nil {
		t.Fatal(err)
	}
	if err := sftp.Chown(f.Name(), toUid, toGid); err == nil {
		t.Fatal("expected error")
	}
}
Example #5
0
func (s *FileTestSuite) TestSetUserConfig_Present(c *C) {
	args := haiconf.CommandArgs{
		"Path":   "/foo.txt",
		"Ensure": haiconf.ENSURE_PRESENT,
		"Mode":   "0777",
		"Owner":  "nobody",
		"Group":  "nogroup",
		"Source": "/foo",
	}

	err := s.f.SetUserConfig(args)
	c.Assert(err, IsNil)

	u, err := user.Lookup("nobody")
	c.Assert(err, IsNil)

	g, err := hacks.LookupSystemGroup("nogroup")
	c.Assert(err, IsNil)

	c.Assert(s.f.Path, Equals, args["Path"])
	c.Assert(s.f.Mode, Equals, os.FileMode(0777))
	c.Assert(s.f.Owner, DeepEquals, u)
	c.Assert(s.f.Group, DeepEquals, g)
	c.Assert(s.f.Source, DeepEquals, args["Source"])
	c.Assert(s.f.Ensure, Equals, args["Ensure"])
}
Example #6
0
func startAPIService(t *testing.T, ctx *testutils.RktRunCtx) *gexpect.ExpectSubprocess {
	noUidGid := false
	gid, err := common.LookupGid(common.RktGroup)
	if err != nil {
		t.Logf("no %q group, will run api service with root, ONLY DO THIS FOR TESTING!", common.RktGroup)
		noUidGid = true
	} else {
		if err := ctx.SetupDataDir(); err != nil {
			t.Fatalf("failed to setup data directory: %v", err)
		}
	}

	u, err := user.Lookup("nobody")
	if err != nil {
		t.Logf(`no "nobody" user, will run api service with root, ONLY DO THIS FOR TESTING!`)
		noUidGid = true
	}
	uid, err := strconv.Atoi(u.Uid)
	if err != nil {
		t.Fatalf(`failed to parse "nobody" UID: %v`, err)
	}

	t.Logf("Running rkt api service")
	apisvcCmd := fmt.Sprintf("%s api-service", ctx.Cmd())

	if noUidGid {
		return startRktAndCheckOutput(t, apisvcCmd, "API service running")
	}
	return startRktAsUidGidAndCheckOutput(t, apisvcCmd, "API service running", false, uid, gid)
}
Example #7
0
func (s *DirectoryTestSuite) TestSetUserConfig_Complete(c *C) {
	args := haiconf.CommandArgs{
		"Path":    "/foo",
		"Ensure":  haiconf.ENSURE_PRESENT,
		"Recurse": true,
		"Mode":    "0777",
		"Owner":   "nobody",
		"Group":   "nogroup",
	}

	err := s.d.SetUserConfig(args)
	c.Assert(err, IsNil)

	u, err := user.Lookup("nobody")
	c.Assert(err, IsNil)

	g, err := hacks.LookupSystemGroup("nogroup")
	c.Assert(err, IsNil)

	c.Assert(s.d.Path, Equals, args["Path"])
	c.Assert(s.d.Mode, Equals, os.FileMode(0777))
	c.Assert(s.d.Owner, DeepEquals, u)
	c.Assert(s.d.Group, DeepEquals, g)
	c.Assert(s.d.Recurse, Equals, args["Recurse"])
	c.Assert(s.d.Ensure, Equals, args["Ensure"])
}
func TestSuiteLinuxGidMappings() string {
	addTestUser()
	linuxSpec.Spec.Process.Args = []string{"/bin/bash", "-c", "cat /proc/1/gid_map"}
	//get uid&gid of test account
	testuser, _ := user.Lookup("uidgidtest")
	testuidInt, _ := strconv.ParseInt(testuser.Uid, 10, 32)
	testgidInt, _ := strconv.ParseInt(testuser.Uid, 10, 32)
	//change owner of rootfs
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		log.Fatalf("utils.setBind error GOPATH == nil")
	}
	rootfspath := gopath + "/src/github.com/huawei-openlab/oct/tools/runtimeValidator/rootfs"
	utils.SetRight(rootfspath, int32(testuidInt), int32(testgidInt))
	var uid specs.IDMapping = specs.IDMapping{
		HostID:      int32(testuidInt),
		ContainerID: 0,
		Size:        10,
	}
	var gid specs.IDMapping = specs.IDMapping{
		HostID:      int32(testgidInt),
		ContainerID: 0,
		Size:        10,
	}
	failinfo := "mapping from Host GID to Container GID failed"
	linuxSpec = setIDmappings(uid, gid)
	result, err := testIDmappings(&linuxSpec, true, failinfo)
	var testResult manager.TestResult
	testResult.Set("TestSuiteLinuxGidMappings", gid, err, result)
	cleanTestUser()
	return testResult.Marshal()

}
// Execute ChownJob.
func (job *ChownJob) Execute() {
	defer job.finalize()
	// -1 means not change.
	uid := -1
	gid := -1
	if job.owner != "" {
		newUser, err := user.Lookup(job.owner)
		if err != nil {
			job.setError(err)
			return
		}
		uid, _ = strconv.Atoi(newUser.Uid)
	}

	if job.group != "" {
		cGroupName := C.CString(job.group)
		defer C.free(unsafe.Pointer(cGroupName))
		group := C.getgrnam(cGroupName)
		if group == nil {
			job.setError(errors.New("no such a group"))
			return
		}
		gid = int(group.gr_gid)
	}

	job.setError(os.Chown(job.file.GetPath(), uid, gid))
}
Example #10
0
// Expand '~'-based homedif from the given path
func ExpandHomedir(s string) (string, error) {
	const (
		slash = string(os.PathSeparator)
		re1   = "~%s"            // regex: /~\//
		re2   = "~([\\w\\-]+)%s" // regex: /~([\w\-]+)\//
	)
	var (
		err error
		re  *regexp.Regexp
		u   *user.User
		rv  string
	)

	if strings.HasPrefix(s, fmt.Sprintf(re1, slash)) {
		u, _ = user.Current()
		rv = fmt.Sprintf("%s", u.HomeDir+s[1:])
		err = nil
	} else if re = regexp.MustCompile(fmt.Sprintf(re2, slash)); re.MatchString(s) {
		uname := re.FindStringSubmatch(s)[0]
		uname = uname[1 : len(uname)-1]
		if u, _ = user.Lookup(uname); u == nil {
			rv = s
			err = nil
		} else {
			rv = u.HomeDir + slash + strings.Join(strings.Split(s, slash)[1:], slash)
			err = nil
		}
	} else if err != nil {
		rv = s
	} else {
		rv = s
		err = nil
	}
	return rv, err
}
Example #11
0
File: paths.go Project: payco/llgo
// userpath takes a path and resolves a leading "~" pattern to
// the current or specified user's home directory. Note that the
// path will not be converted to an absolute path if there is no
// leading "~" pattern.
func userpath(path string) (string, error) {
	if len(path) > 0 && path[0] == '~' {
		slashindex := strings.IndexRune(path, filepath.Separator)
		var username string
		if slashindex == -1 {
			username = path[1:]
		} else {
			username = path[1:slashindex]
		}

		var u *user.User
		var err error
		if username == "" {
			u, err = user.Current()
		} else {
			u, err = user.Lookup(username)
		}
		if err != nil {
			return "", err
		}

		if slashindex == -1 {
			path = u.HomeDir
		} else {
			path = filepath.Join(u.HomeDir, path[slashindex+1:])
		}
	}
	return path, nil
}
Example #12
0
func (opt *UserOption) User() (userinfo *user.User, err error) {
	nvs := strings.TrimSpace(opt.Value)
	if nvs == "" {
		// special case: empty string is the current euid.
		return nil, EmptyUserSet
	}
	// attempt to map this as a number first, in case a numeric UID
	// was provided.
	_, err = strconv.Atoi(nvs)
	if err != nil {
		switch err.(type) {
		case *strconv.NumError:
			// not a number.  do a user table lookup.
			userinfo, err = user.Lookup(nvs)
			if err != nil {
				return nil, err
			}
			return userinfo, nil
		default:
			return nil, err
		}
	}
	userinfo, err = user.LookupId(nvs)
	return userinfo, err
}
Example #13
0
func main() {
	var (
		u        *user.User
		err      error
		username string
		program  string
		command  []string
	)
	if len(os.Args[1:]) < 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s USERNAME COMMAND [args...]\n", os.Args[0])
		os.Exit(1)
	}
	username = os.Args[1]
	program = os.Args[2]
	command = append(command, os.Args[3:]...)
	if u, err = user.Lookup(username); err != nil {
		abort(err)
	}
	if program, err = exec.LookPath(program); err != nil {
		abort(err)
	}
	if err = setupEnv(u); err != nil {
		abort(err)
	}
	fmt.Println("Found binary at", program)
	fmt.Println("Args: ", command)
	if err = syscall.Exec(program, command, os.Environ()); err != nil {
		abort(err)
	}
}
Example #14
0
func SetFileUser(filename, username string, run bool) (bool, error) {
	userData, err := user.Lookup(username)
	if err != nil {
		return false, err
	}
	uid, err := strconv.Atoi(userData.Uid)
	if err != nil {
		return false, err
	}
	var stat syscall.Stat_t
	err = syscall.Stat(filename, &stat)
	if err != nil {
		return false, err
	}
	if int(stat.Uid) == uid {
		return false, nil
	}
	if run {
		err = os.Chown(filename, uid, int(stat.Gid))
		if err != nil {
			return false, err
		}
	}
	return true, nil
}
Example #15
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
}
Example #16
0
func GitoliteTournamentTest(test *testing.T, f func(*testutil.T, *Tournament)) {
	t := (*testutil.T)(test)
	conf := gitoliteTestConf
	conf.AdminKey = testutil.PathRelativeToUserHome(t, conf.AdminKey)
	conf.SSHKey = testutil.PathRelativeToUserHome(t, conf.SSHKey)
	if host, err := git.CreateGitoliteHost(conf); err != nil {
		t.ErrorNow(err)
	} else if _, err := user.Lookup(host.User); err != nil {
		switch err.(type) {
		case user.UnknownUserError:
			t.Skipf("%v, skipping gitolite tests", err)
			t.SkipNow()
		default:
			t.ErrorNow(err)
		}
	} else if err := host.Reset(); err != nil {
		t.ErrorNow(err)
	} else {
		defer host.Cleanup()
		dummyArena := arena.DummyArena{time.Now(), arena.MatchResult{arena.WinnerA, arena.ReasonVictory, []byte("MATCH_RESULT")}, nil}
		remote := git.TempRemote{}
		bootstrap := &arena.MinimalBootstrap{"../arena/internal/categories"}
		if database, err := NewInMemoryDatabase(); err != nil {
			t.ErrorNow(err)
		} else if err = database.MigrateSchema(); err != nil {
			t.ErrorNow(err)
		} else {
			tournament := NewTournament(database, dummyArena, bootstrap, host, remote)
			f(t, tournament)
		}
	}
}
Example #17
0
func mktmpdir(home string) string {
	dst := path.Join(home, "tmp")
	err := os.MkdirAll(dst, 0700)
	if err != nil {
		log.Panicln("Making tmpdir %q", err)
	}

	u, err := user.Lookup(pamUser)
	if err != nil {
		log.Panicln("Lookup UID %v: %q", pamUser, err)
	}

	var uid int
	_, err = fmt.Sscan(u.Uid, &uid)
	if err != nil {
		log.Panicln("Parsing UID %q: ", u.Uid, err)
	}

	err = os.Chown(dst, uid, databoxGid)
	if err != nil {
		log.Panicln("Chown(%q, %v, %v) = %q", dst, uid, databoxGid, err)
	}

	return dst
}
Example #18
0
func NewWorkerDaemon(options *WorkerOptions) *WorkerDaemon {
	if options.FileContentCount == 0 {
		options.FileContentCount = 1024
	}

	cache := NewContentCache(options.CacheDir)
	cache.SetMemoryCacheSize(options.FileContentCount)
	me := &WorkerDaemon{
		secret:        options.Secret,
		contentCache:  cache,
		mirrorMap:     make(map[string]*Mirror),
		contentServer: &ContentServer{Cache: cache},
		pending:       NewPendingConnections(),
		maxJobCount:   options.Jobs,
		tmpDir:        options.TempDir,
		rpcServer:     rpc.NewServer(),
	}
	if os.Geteuid() == 0 && options.User != nil {
		nobody, err := user.Lookup(*options.User)
		if err != nil {
			log.Fatalf("can't lookup %q: %v", options.User, err)
		}
		me.Nobody = nobody
	}
	me.cond = sync.NewCond(&me.mirrorMapMutex)
	me.stopListener = make(chan int, 1)
	me.rpcServer.Register(me)
	return me
}
func (s *executor) getAuthConfig(imageName string) (docker.AuthConfiguration, error) {
	homeDir := homedir.Get()
	if s.Shell().User != "" {
		u, err := user.Lookup(s.Shell().User)
		if err != nil {
			return docker.AuthConfiguration{}, err
		}
		homeDir = u.HomeDir
	}
	if homeDir == "" {
		return docker.AuthConfiguration{}, fmt.Errorf("Failed to get home directory")
	}

	indexName, _ := docker_helpers.SplitDockerImageName(imageName)

	authConfigs, err := docker_helpers.ReadDockerAuthConfigs(homeDir)
	if err != nil {
		// ignore doesn't exist errors
		if os.IsNotExist(err) {
			err = nil
		}
		return docker.AuthConfiguration{}, err
	}

	authConfig := docker_helpers.ResolveDockerAuthConfig(indexName, authConfigs)
	if authConfig != nil {
		s.Debugln("Using", authConfig.Username, "to connect to", authConfig.ServerAddress, "in order to resolve", imageName, "...")
		return *authConfig, nil
	}

	return docker.AuthConfiguration{}, fmt.Errorf("No credentials found for %v", indexName)
}
Example #20
0
// ParseFilepath expands ~ and ~user constructions.
// If user or $HOME is unknown, do nothing.
func ParseFilepath(path string) string {
	if !strings.HasPrefix(path, "~") {
		return path
	}
	i := strings.Index(path, "/")
	if i < 0 {
		i = len(path)
	}
	var home string
	if i == 1 {
		if home = os.Getenv("HOME"); home == "" {
			usr, err := user.Current()
			if err != nil {
				log.V(1).Infof("Failed to get current home directory: %v", err)
				return path
			}
			home = usr.HomeDir
		}
	} else {
		usr, err := user.Lookup(path[1:i])
		if err != nil {
			log.V(1).Infof("Failed to get %v's home directory: %v", path[1:i], err)
			return path
		}
		home = usr.HomeDir
	}
	path = filepath.Join(home, path[i:])
	return path
}
Example #21
0
// RoleToID converts username/groupname to their numeric id representations: uid/gid
// Returns error if the role is not supported, usernamd/groupname have not been found
func RoleToID(role string, name string) (uint64, error) {
	var id string
	switch strings.ToLower(role) {
	case "user":
		user, err := user.Lookup(name)
		if err != nil {
			return 0, err
		}
		id = user.Uid
	case "group":
		group, err := group.Lookup(name)
		if err != nil {
			return 0, err
		}
		id = group.Gid
	default:
		return 0, fmt.Errorf("Unsupported role: %s", role)
	}
	// Parse uid/gid
	numID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		return 0, err
	}

	return numID, nil
}
Example #22
0
func (d *AllocDir) dropDirPermissions(path string) error {
	// Can't do anything if not root.
	if unix.Geteuid() != 0 {
		return nil
	}

	u, err := user.Lookup("nobody")
	if err != nil {
		return err
	}

	uid, err := getUid(u)
	if err != nil {
		return err
	}

	gid, err := getGid(u)
	if err != nil {
		return err
	}

	if err := os.Chown(path, uid, gid); err != nil {
		return fmt.Errorf("Couldn't change owner/group of %v to (uid: %v, gid: %v): %v", path, uid, gid, err)
	}

	if err := os.Chmod(path, 0777); err != nil {
		return fmt.Errorf("Chmod(%v) failed: %v", path, err)
	}

	return nil
}
Example #23
0
func (e *LinuxExecutor) runAs(userid string) error {
	errs := new(multierror.Error)

	// First, try to lookup the user by uid
	u, err := user.LookupId(userid)
	if err == nil {
		e.user = u
		return nil
	} else {
		errs = multierror.Append(errs, err)
	}

	// Lookup failed, so try by username instead
	u, err = user.Lookup(userid)
	if err == nil {
		e.user = u
		return nil
	} else {
		errs = multierror.Append(errs, err)
	}

	// If we got here we failed to lookup based on id and username, so we'll
	// return those errors.
	return fmt.Errorf("Failed to identify user to run as: %s", errs)
}
Example #24
0
// runAs takes a user id as a string and looks up the user, and sets the command
// to execute as that user.
func (e *UniversalExecutor) runAs(userid string) error {
	u, err := user.Lookup(userid)
	if err != nil {
		return fmt.Errorf("Failed to identify user %v: %v", userid, err)
	}

	// Convert the uid and gid
	uid, err := strconv.ParseUint(u.Uid, 10, 32)
	if err != nil {
		return fmt.Errorf("Unable to convert userid to uint32: %s", err)
	}
	gid, err := strconv.ParseUint(u.Gid, 10, 32)
	if err != nil {
		return fmt.Errorf("Unable to convert groupid to uint32: %s", err)
	}

	// Set the command to run as that user and group.
	if e.cmd.SysProcAttr == nil {
		e.cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	if e.cmd.SysProcAttr.Credential == nil {
		e.cmd.SysProcAttr.Credential = &syscall.Credential{}
	}
	e.cmd.SysProcAttr.Credential.Uid = uint32(uid)
	e.cmd.SysProcAttr.Credential.Gid = uint32(gid)

	return nil
}
Example #25
0
func (fs osFileSystem) Chown(path, username string) (err error) {
	fs.logger.Debug(fs.logTag, "Chown %s to user %s", path, username)

	user, err := osuser.Lookup(username)
	if err != nil {
		err = bosherr.WrapError(err, "Looking up user %s", username)
		return
	}

	uid, err := strconv.Atoi(user.Uid)
	if err != nil {
		err = bosherr.WrapError(err, "Converting UID to integer")
		return
	}

	gid, err := strconv.Atoi(user.Gid)
	if err != nil {
		err = bosherr.WrapError(err, "Converting GID to integer")
		return
	}

	err = os.Chown(path, uid, gid)
	if err != nil {
		err = bosherr.WrapError(err, "Doing Chown")
		return
	}
	return
}
Example #26
0
func ChangePerm(owner string, suid, sgid int) (uid, gid int, err error) {
	var u *user.User
	switch {
	case owner != "" && suid != 0:
		err = fmt.Errorf("both uid and owner is specified. owner:%s,uid:%d", owner, suid)
		return
	case owner == "" && suid == 0 && sgid == 0:
		if u, err = user.Current(); err != nil {
			return
		}
		uid, _ = strconv.Atoi(u.Uid)
		gid, _ = strconv.Atoi(u.Gid)
	case owner != "":
		if u, err = user.Lookup(owner); err != nil {
			return
		}
		uid, _ = strconv.Atoi(u.Uid)
		if sgid != 0 {
			gid = sgid
		} else {
			gid, _ = strconv.Atoi(u.Gid)
		}
	default:
		uid = suid
		gid = sgid
	}
	return
}
func (s *DockerExecutor) getAuthConfig(imageName string) (docker.AuthConfiguration, error) {
	user, err := u.Current()
	if s.Shell.User != nil {
		user, err = u.Lookup(*s.Shell.User)
	}
	if err != nil {
		return docker.AuthConfiguration{}, err
	}

	indexName, _ := docker_helpers.SplitDockerImageName(imageName)

	authConfigs, err := docker_helpers.ReadDockerAuthConfigs(user.HomeDir)
	if err != nil {
		// ignore doesn't exist errors
		if os.IsNotExist(err) {
			err = nil
		}
		return docker.AuthConfiguration{}, err
	}

	authConfig := docker_helpers.ResolveDockerAuthConfig(indexName, authConfigs)
	if authConfig != nil {
		s.Debugln("Using", authConfig.Username, "to connect to", authConfig.ServerAddress, "in order to resolve", imageName, "...")
		return *authConfig, nil
	}

	return docker.AuthConfiguration{}, fmt.Errorf("No credentials found for %v", indexName)
}
// CreateUser will create a new user, with the given homeFolder, set the user
// owner of the homeFolder, and assign the user membership of given groups.
func CreateUser(homeFolder string, groups []*Group) (*User, error) {
	// Prepare arguments
	args := formatArgs(map[string]string{
		"-d": homeFolder,   // Set home folder
		"-c": "task user",  // Comment
		"-s": defaultShell, // Set default shell
	})
	args = append(args, "-M") // Don't create home, ignoring any global settings
	args = append(args, "-U") // Create primary user-group with same name
	if len(groups) > 0 {
		gids := []string{}
		for _, g := range groups {
			gids = append(gids, strconv.Itoa(g.gid))
		}
		args = append(args, "-G", strings.Join(gids, ","))
	}

	// Generate a random username
	name := slugid.Nice()
	args = append(args, name)

	// Run useradd command
	_, err := exec.Command(systemUserAdd, args...).Output()
	if err != nil {
		if e, ok := err.(*exec.ExitError); ok {
			return nil, fmt.Errorf(
				"Failed to create user with useradd, stderr: '%s'", string(e.Stderr),
			)
		}
		return nil, fmt.Errorf("Failed to run useradd, error: %s", err)
	}

	// Lookup user to get the uid
	u, err := user.Lookup(name)
	if err != nil {
		panic(fmt.Sprintf(
			"Failed to lookup newly created user: '******', error: %s",
			name, err,
		))
	}

	// Parse uid/gid
	uid, err := strconv.ParseUint(u.Uid, 10, 32)
	if err != nil {
		panic(fmt.Sprintf("user.Uid should be an integer on POSIX systems"))
	}
	gid, err := strconv.ParseUint(u.Gid, 10, 32)
	if err != nil {
		panic(fmt.Sprintf("user.Gid should be an integer on POSIX systems"))
	}
	debug("Created user with uid: %d, gid: %d, name: %s", uid, gid, name)

	// Set user as owner of home folder
	err = os.Chown(homeFolder, int(uid), int(gid))
	if err != nil {
		return nil, fmt.Errorf("Failed to chown homeFolder, error: %s", err)
	}

	return &User{uint32(uid), uint32(gid), name, homeFolder}, nil
}
Example #29
0
File: user.go Project: postfix/goss
func (u *User) Exists() (interface{}, error) {
	_, err := user.Lookup(u.username)
	if err != nil {
		return false, nil
	}
	return true, nil
}
Example #30
0
// Takes care of dropping privileges to the desired user
func changeUser(u string) {
	if u == "" {
		return
	}
	userent, err := user.LookupId(u)
	if err != nil {
		userent, err = user.Lookup(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)
	}
}