AB#2046 : Add option to create SSH users for the first coordinator upon initialization (#133)

* Move `file`, `ssh` and `user` packages to internal
* Rename `SSHKey` to `(ssh.)UserKey`
* Rename KeyValue / Publickey to PublicKey
* Rename SSH key file from "debugd" to "ssh-keys"
* Add CreateSSHUsers function to Core
* Call CreateSSHUsers users on first control-plane node, when defined in config

Tests:
* Make StubUserCreator add entries to /etc/passwd
* Add NewLinuxUserManagerFake for unit tests
* Add unit tests & adjust existing ones to changes
This commit is contained in:
Nils Hanke 2022-05-16 17:32:00 +02:00 committed by GitHub
parent 5dc2e71d80
commit 68092f27dd
63 changed files with 879 additions and 554 deletions

View file

@ -1,25 +0,0 @@
package createuser
import (
"context"
"fmt"
"os/exec"
)
type Unix struct{}
// reference: https://man7.org/linux/man-pages/man8/useradd.8.html#EXIT_VALUES
const exitCodeUsernameAlreadyInUse = 9
// CreateUser creates a new user with sudo access. Returns successfully if creation succeeds or user existed already.
func (u Unix) CreateUser(ctx context.Context, username string) error {
cmd := exec.CommandContext(ctx, "useradd", "-m", "-G", "wheel,sudo", username)
if err := cmd.Run(); err != nil {
// do not fail if user already exists
if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == exitCodeUsernameAlreadyInUse {
return nil
}
return fmt.Errorf("creating a new user failed: %w", err)
}
return nil
}

View file

@ -1,84 +0,0 @@
package deploy
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/edgelesssys/constellation/debugd/debugd/deploy/createuser"
"github.com/edgelesssys/constellation/debugd/debugd/deploy/passwd"
"github.com/spf13/afero"
)
// ErrUserDoesNotExist is returned by GetLinuxUser if a linux user does not exist yet.
var ErrUserDoesNotExist = errors.New("user does not exist")
type passwdParser interface {
Parse(fs afero.Fs) (passwd.Entries, error)
}
type userCreator interface {
CreateUser(ctx context.Context, username string) error
}
// LinuxUser holds relevant information about a linux user (subset of /etc/passwd).
type LinuxUser struct {
Username string
Home string
Uid int
Gid int
}
// LinuxUserManager can retrieve information on linux users and create new users.
type LinuxUserManager struct {
fs afero.Fs
passwd passwdParser
creator userCreator
}
// NewLinuxUserManager creates a new LinuxUserManager.
func NewLinuxUserManager(fs afero.Fs) *LinuxUserManager {
return &LinuxUserManager{
fs: fs,
passwd: passwd.Passwd{},
creator: createuser.Unix{},
}
}
// getLinuxUser tries to find an existing linux user in /etc/passwd.
func (l *LinuxUserManager) getLinuxUser(username string) (LinuxUser, error) {
entries, err := l.passwd.Parse(l.fs)
if err != nil {
return LinuxUser{}, err
}
if _, ok := entries[username]; !ok {
return LinuxUser{}, ErrUserDoesNotExist
}
entry := entries[username]
uid, err := strconv.Atoi(entry.Uid)
if err != nil {
return LinuxUser{}, fmt.Errorf("failed to parse users uid: %w", err)
}
gid, err := strconv.Atoi(entry.Gid)
if err != nil {
return LinuxUser{}, fmt.Errorf("failed to parse users gid: %w", err)
}
return LinuxUser{
Username: username,
Home: entry.Home,
Uid: uid,
Gid: gid,
}, nil
}
// EnsureLinuxUserExists will try to create the user specified by username and call GetLinuxUser to retrieve user information.
func (l *LinuxUserManager) EnsureLinuxUserExists(ctx context.Context, username string) (LinuxUser, error) {
// try to create user (even if it already exists)
if err := l.creator.CreateUser(ctx, username); err != nil {
return LinuxUser{}, err
}
return l.getLinuxUser(username)
}

View file

@ -1,142 +0,0 @@
package deploy
import (
"context"
"errors"
"testing"
"github.com/edgelesssys/constellation/debugd/debugd/deploy/passwd"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetLinuxUser(t *testing.T) {
username := "user"
testCases := map[string]struct {
userCreator *stubUserCreator
passwdContents string
wantErr bool
wantUser LinuxUser
}{
"get works": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
wantErr: false,
wantUser: LinuxUser{
Username: "user",
Home: "/home/user",
Uid: 1000,
Gid: 1000,
},
},
"user does not exist": {
userCreator: &stubUserCreator{},
passwdContents: "",
wantErr: true,
},
"parse fails": {
userCreator: &stubUserCreator{},
passwdContents: "invalid contents\n",
wantErr: true,
},
"invalid uid": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:invalid:1000:user:/home/user:/bin/bash\n",
wantErr: true,
},
"invalid gid": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:invalid:user:/home/user:/bin/bash\n",
wantErr: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
fs := afero.NewMemMapFs()
assert.NoError(afero.WriteFile(fs, "/etc/passwd", []byte(tc.passwdContents), 0o755))
manager := LinuxUserManager{
fs: fs,
passwd: passwd.Passwd{},
creator: tc.userCreator,
}
user, err := manager.getLinuxUser(username)
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.wantUser, user)
})
}
}
func TestEnsureLinuxUserExists(t *testing.T) {
username := "user"
testCases := map[string]struct {
userCreator *stubUserCreator
passwdContents string
wantErr bool
wantUser LinuxUser
}{
"create works": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
wantErr: false,
wantUser: LinuxUser{
Username: "user",
Home: "/home/user",
Uid: 1000,
Gid: 1000,
},
},
"create fails": {
userCreator: &stubUserCreator{
createUserErr: errors.New("create fails"),
},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
wantErr: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
fs := afero.NewMemMapFs()
assert.NoError(afero.WriteFile(fs, "/etc/passwd", []byte(tc.passwdContents), 0o755))
manager := LinuxUserManager{
fs: fs,
passwd: passwd.Passwd{},
creator: tc.userCreator,
}
user, err := manager.EnsureLinuxUserExists(context.Background(), username)
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.wantUser, user)
assert.ElementsMatch([]string{username}, tc.userCreator.usernames)
})
}
}
type stubUserCreator struct {
usernames []string
createUserErr error
}
func (s *stubUserCreator) CreateUser(ctx context.Context, username string) error {
s.usernames = append(s.usernames, username)
return s.createUserErr
}

View file

@ -1,28 +0,0 @@
package passwd
import (
"github.com/spf13/afero"
"github.com/willdonnelly/passwd"
)
// An Entry contains all the fields for a specific user. Re-exported to allow other module to only import this passwd module.
type Entries map[string]passwd.Entry
type Passwd struct{}
// Parse opens the '/etc/passwd' file and parses it into a map from usernames to Entries.
func (p Passwd) Parse(fs afero.Fs) (Entries, error) {
return p.parseFile(fs, "/etc/passwd")
}
// parseFile opens the file and parses it into a map from usernames to Entries.
func (p Passwd) parseFile(fs afero.Fs, path string) (Entries, error) {
file, err := fs.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
entries, err := passwd.ParseReader(file)
return Entries(entries), err
}

View file

@ -1,66 +0,0 @@
package passwd
import (
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParse(t *testing.T) {
filename := "/etc/passwd"
testCases := map[string]struct {
passwdContents string
createFile bool
wantEntries Entries
wantErr bool
}{
"parse works": {
passwdContents: "root:x:0:0:root:/root:/bin/bash\n",
createFile: true,
wantEntries: Entries{
"root": {
Pass: "x",
Uid: "0",
Gid: "0",
Gecos: "root",
Home: "/root",
Shell: "/bin/bash",
},
},
wantErr: false,
},
"passwd is corrupt": {
passwdContents: "too:few:fields\n",
createFile: true,
wantErr: true,
},
"file does not exist": {
createFile: false,
wantErr: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
fs := afero.NewMemMapFs()
if tc.createFile {
assert.NoError(afero.WriteFile(fs, filename, []byte(tc.passwdContents), 0o644))
}
passwd := Passwd{}
entries, err := passwd.Parse(fs)
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.wantEntries, entries)
})
}
}

View file

@ -1,94 +0,0 @@
package deploy
import (
"context"
"fmt"
"log"
"os"
"sync"
"github.com/edgelesssys/constellation/debugd/debugd/deploy/createuser"
"github.com/edgelesssys/constellation/debugd/debugd/deploy/passwd"
"github.com/edgelesssys/constellation/debugd/ssh"
"github.com/spf13/afero"
)
// SSHAccess reads ssh public keys from a channel, creates the specified users if required and writes the public keys to the users authorized_keys file.
type SSHAccess struct {
fs afero.Fs
userManager LinuxUserManager
authorized map[string]bool
mux sync.Mutex
}
// NewSSHAccess creates a new SSHAccess.
func NewSSHAccess(fs afero.Fs) *SSHAccess {
return &SSHAccess{
fs: fs,
userManager: LinuxUserManager{
fs: fs,
passwd: passwd.Passwd{},
creator: createuser.Unix{},
},
mux: sync.Mutex{},
authorized: map[string]bool{},
}
}
// alreadyAuthorized checks if key was written to authorized keys before.
func (s *SSHAccess) alreadyAuthorized(sshKey ssh.SSHKey) bool {
_, ok := s.authorized[fmt.Sprintf("%s:%s", sshKey.Username, sshKey.KeyValue)]
return ok
}
// rememberAuthorized marks this key as already written to authorized keys..
func (s *SSHAccess) rememberAuthorized(sshKey ssh.SSHKey) {
s.authorized[fmt.Sprintf("%s:%s", sshKey.Username, sshKey.KeyValue)] = true
}
func (s *SSHAccess) DeploySSHAuthorizedKey(ctx context.Context, sshKey ssh.SSHKey) error {
// allow only one thread to write to authorized keys, create users and update the authorized map at a time
s.mux.Lock()
defer s.mux.Unlock()
if s.alreadyAuthorized(sshKey) {
return nil
}
log.Printf("Trying to deploy ssh key for %s\n", sshKey.Username)
user, err := s.userManager.EnsureLinuxUserExists(ctx, sshKey.Username)
if err != nil {
return err
}
// CoreOS uses https://github.com/coreos/ssh-key-dir to search for ssh keys in ~/.ssh/authorized_keys.d/*
sshFolder := fmt.Sprintf("%s/.ssh", user.Home)
authorized_keys_d := fmt.Sprintf("%s/authorized_keys.d", sshFolder)
if err := s.fs.MkdirAll(authorized_keys_d, 0o700); err != nil {
return err
}
if err := s.fs.Chown(sshFolder, user.Uid, user.Gid); err != nil {
return err
}
if err := s.fs.Chown(authorized_keys_d, user.Uid, user.Gid); err != nil {
return err
}
authorizedKeysPath := fmt.Sprintf("%s/debugd", authorized_keys_d)
authorizedKeysFile, err := s.fs.OpenFile(authorizedKeysPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return err
}
_, err = authorizedKeysFile.WriteString(fmt.Sprintf("%s %s\n", sshKey.KeyValue, sshKey.Username))
if err != nil {
return err
}
if err := authorizedKeysFile.Close(); err != nil {
return err
}
if err := s.fs.Chown(authorizedKeysPath, user.Uid, user.Gid); err != nil {
return err
}
if err := s.fs.Chmod(authorizedKeysPath, 0o644); err != nil {
return err
}
s.rememberAuthorized(sshKey)
log.Printf("Successfully authorized %s\n", sshKey.Username)
return nil
}

View file

@ -1,120 +0,0 @@
package deploy
import (
"context"
"sync"
"testing"
"github.com/edgelesssys/constellation/debugd/debugd/deploy/passwd"
"github.com/edgelesssys/constellation/debugd/ssh"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDeploySSHAuthorizedKey(t *testing.T) {
authorizedKey := ssh.SSHKey{
Username: "user",
KeyValue: "ssh-rsa testkey",
}
testCases := map[string]struct {
fs afero.Fs
userCreator *stubUserCreator
passwdContents string
alreadyDeployed bool
readonly bool
wantErr bool
wantFile bool
wantFileContents string
}{
"deploy works": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
wantErr: false,
wantFile: true,
wantFileContents: "ssh-rsa testkey user\n",
},
"appending ssh key works": {
fs: memMapFsWithFile("/home/user/.ssh/authorized_keys.d/debugd", "ssh-rsa preexistingkey user\n"),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
wantErr: false,
wantFile: true,
wantFileContents: "ssh-rsa preexistingkey user\nssh-rsa testkey user\n",
},
"redeployment avoided": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
wantErr: false,
alreadyDeployed: true,
wantFile: false,
},
"user does not exist": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "",
wantErr: true,
},
"readonly fs": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
readonly: true,
wantErr: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
assert.NoError(afero.WriteFile(tc.fs, "/etc/passwd", []byte(tc.passwdContents), 0o755))
if tc.readonly {
tc.fs = afero.NewReadOnlyFs(tc.fs)
}
authorized := map[string]bool{}
if tc.alreadyDeployed {
authorized["user:ssh-rsa testkey"] = true
}
sshAccess := SSHAccess{
fs: tc.fs,
userManager: LinuxUserManager{
fs: tc.fs,
passwd: passwd.Passwd{},
creator: tc.userCreator,
},
mux: sync.Mutex{},
authorized: authorized,
}
err := sshAccess.DeploySSHAuthorizedKey(context.Background(), authorizedKey)
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
if tc.wantFile {
fileContents, err := afero.ReadFile(tc.fs, "/home/user/.ssh/authorized_keys.d/debugd")
assert.NoError(err)
assert.Equal(tc.wantFileContents, string(fileContents))
} else {
exists, err := afero.Exists(tc.fs, "/home/user/.ssh/authorized_keys.d/debugd")
assert.NoError(err)
assert.False(exists)
}
})
}
}
func memMapFsWithFile(path string, contents string) afero.Fs {
fs := afero.NewMemMapFs()
err := afero.WriteFile(fs, path, []byte(contents), 0o755)
if err != nil {
panic(err)
}
return fs
}