Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resolve homedir of sudo user #1412

Merged
merged 4 commits into from
May 30, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions clab/authz_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net"
"os"
"os/user"
"path/filepath"
"strings"

Expand All @@ -18,24 +19,35 @@ import (
)

const (
pubKeysGlob = "~/.ssh/*.pub"
pubKeysGlobPart = ".ssh/*.pub"
// authorized keys file path on a clab host that is used to create the clabAuthzKeys file.
authzKeysFPath = "~/.ssh/authorized_keys"
authzKeysFPathPart = ".ssh/authorized_keys"
)

// CreateAuthzKeysFile creats the authorized_keys file in the lab directory
// if any files ~/.ssh/*.pub found.
func (c *CLab) CreateAuthzKeysFile() error {
b := new(bytes.Buffer)

p := utils.ResolvePath(pubKeysGlob, "")
userId, isSet := os.LookupEnv("SUDO_UID")
if !isSet {
userId = "0" // default to root
}

// lookup user to figure out Home Directory
u, err := user.LookupId(userId)
if err != nil {
return err
}

p := utils.ResolvePath(filepath.Join(u.HomeDir, pubKeysGlobPart), "")
hellt marked this conversation as resolved.
Show resolved Hide resolved

all, err := filepath.Glob(p)
if err != nil {
return fmt.Errorf("failed globbing the path %s", p)
}

f := utils.ResolvePath(authzKeysFPath, "")
f := utils.ResolvePath(filepath.Join(u.HomeDir, authzKeysFPathPart), "")

if utils.FileExists(f) {
log.Debugf("%s found, adding the public keys it contains", f)
Expand All @@ -50,7 +62,7 @@ func (c *CLab) CreateAuthzKeysFile() error {

log.Debugf("extracted %d keys from ssh-agent", len(keys))
for _, k := range keys {
b.WriteString(k + "\n")
addKeyToBuffer(b, k)
}

for _, fn := range all {
Expand Down Expand Up @@ -79,8 +91,7 @@ func addKeyToBuffer(b *bytes.Buffer, key string) {
return
}

key = elems[0] + " " + elems[1]
if !strings.Contains(b.String(), key) {
if !strings.Contains(b.String(), elems[1]) {
b.WriteString(key + "\n")
}
}
Expand Down