Skip to content

Commit

Permalink
Merge pull request #1388 from srl-labs/sshpubkeysfromagent
Browse files Browse the repository at this point in the history
extract ssh pub keys also from agent
  • Loading branch information
hellt committed May 16, 2023
2 parents 8c91af2 + 4134107 commit 13346db
Showing 1 changed file with 52 additions and 9 deletions.
61 changes: 52 additions & 9 deletions clab/authz_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ package clab
import (
"bytes"
"fmt"
"net"
"os"
"path/filepath"
"strings"

log "github.com/sirupsen/logrus"
"github.com/srl-labs/containerlab/utils"
"golang.org/x/crypto/ssh/agent"
)

const (
Expand Down Expand Up @@ -39,24 +42,25 @@ func (c *CLab) CreateAuthzKeysFile() error {
all = append(all, f)
}

if len(all) == 0 {
log.Debug("no public keys found")
return nil
// get keys registered with ssh-agent
keys, err := SSHAgentKeys()
if err != nil {
log.Debug(err)
}

log.Debugf("found public key files %q", all)
log.Debugf("extracted %d keys from ssh-agent", len(keys))
for _, k := range keys {
b.WriteString(k + "\n")

}

for _, fn := range all {
rb, err := os.ReadFile(fn)
if err != nil {
return fmt.Errorf("failed reading the file %s: %v", fn, err)
}
// ensure the key ends with a newline
if !bytes.HasSuffix(rb, []byte("\n")) {
rb = append(rb, []byte("\n")...)
}

b.Write(rb)
addKeyToBuffer(b, string(rb))
}

clabAuthzKeysFPath := c.TopoPaths.AuthorizedKeysFilename()
Expand All @@ -67,3 +71,42 @@ func (c *CLab) CreateAuthzKeysFile() error {
// ensure authz_keys will have the permissions allowing it to be read by anyone
return os.Chmod(clabAuthzKeysFPath, 0644) // skipcq: GSC-G302
}

// addKeyToBuffer adds a key to the buffer if the key is not already present
func addKeyToBuffer(b *bytes.Buffer, key string) {
// since they key might have a comment as a third field, we need to strip it
elems := strings.Fields(key)
if len(elems) < 2 {
return
}

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

// SSHAgentKeys retrieves public keys registered with the ssh-agent
func SSHAgentKeys() ([]string, error) {
socket := os.Getenv("SSH_AUTH_SOCK")
if len(socket) == 0 {
return nil, fmt.Errorf("SSH_AUTH_SOCK not set, skipping pubkey fetching")
}
conn, err := net.Dial("unix", socket)
if err != nil {
return nil, fmt.Errorf("failed to open SSH_AUTH_SOCK: %w", err)
}

agentClient := agent.NewClient(conn)
keys, err := agentClient.List()
if err != nil {
return nil, fmt.Errorf("error listing agent's pub keys %w", err)
}

var pubKeys []string
for _, key := range keys {
pubKeys = append(pubKeys, key.String())
}

return pubKeys, nil
}

0 comments on commit 13346db

Please sign in to comment.