Skip to content

Commit

Permalink
ssh agent support
Browse files Browse the repository at this point in the history
  • Loading branch information
TP Honey committed Jan 23, 2023
1 parent 84d8664 commit a2f8157
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 50 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
release
coverage.out
vendor
.vscode/
Dockerfile
10 changes: 5 additions & 5 deletions cmd/drone-docker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,10 @@ func main() {
Usage: "platform value to pass to docker",
EnvVar: "PLUGIN_PLATFORM",
},
cli.StringSliceFlag{
Name: "ssh-agent",
Usage: "mount ssh agent",
EnvVar: "PLUGIN_SSH_AGENT",
cli.StringFlag{
Name: "ssh-agent-key",
Usage: "base64 encoded ssh agent key to use",
EnvVar: "PLUGIN_SSH_AGENT_KEY",
},
}

Expand Down Expand Up @@ -323,7 +323,7 @@ func run(c *cli.Context) error {
AddHost: c.StringSlice("add-host"),
Quiet: c.Bool("quiet"),
Platform: c.String("platform"),
SSHAgent: c.StringSlice("ssh-agent"),
SSHAgentKey: c.String("ssh-agent-key"),
},
Daemon: docker.Daemon{
Registry: c.String("docker.registry"),
Expand Down
7 changes: 4 additions & 3 deletions daemon.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//go:build !windows
// +build !windows

package docker

import (
"io/ioutil"
"io"
"os"
)

Expand All @@ -17,8 +18,8 @@ func (p Plugin) startDaemon() {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
} else {
cmd.Stdout = ioutil.Discard
cmd.Stderr = ioutil.Discard
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
}
go func() {
trace(cmd)
Expand Down
67 changes: 25 additions & 42 deletions docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package docker
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
Expand All @@ -13,11 +11,6 @@ import (
"time"
)

const (
SSHAgentSockPath = "/tmp/drone-ssh-agent-sock"
SSHPrivateKeyFromEnv = "SSH_KEY"
)

type (
// Daemon defines Docker daemon parameters.
Daemon struct {
Expand Down Expand Up @@ -71,7 +64,8 @@ type (
AddHost []string // Docker build add-host
Quiet bool // Docker build quiet
Platform string // Docker build platform
SSHAgent []string // Docker build ssh
SSHAgentKey string // Docker build ssh agent key
SSHKeyPath string // Docker build ssh key path
}

// Plugin defines the Docker plugin parameters.
Expand Down Expand Up @@ -153,7 +147,7 @@ func (p Plugin) Exec() error {
os.MkdirAll(dockerHome, 0600)

path := filepath.Join(dockerHome, "config.json")
err := ioutil.WriteFile(path, []byte(p.Login.Config), 0600)
err := os.WriteFile(path, []byte(p.Login.Config), 0600)
if err != nil {
return fmt.Errorf("Error writing config.json: %s", err)
}
Expand Down Expand Up @@ -189,10 +183,12 @@ func (p Plugin) Exec() error {
}

// setup for using ssh agent (https://docs.docker.com/develop/develop-images/build_enhancements/#using-ssh-to-access-private-data-in-builds)

if len(p.Build.SSHAgent) > 0 {
fmt.Printf("ssh agent set to \"%s\"\n", p.Build.SSHAgent)
cmds = append(cmds, commandSSHAgentForwardingSetup(p.Build)...)
if p.Build.SSHAgentKey != "" {
var sshErr error
p.Build.SSHKeyPath, sshErr = writeSSHPrivateKey(p.Build.SSHAgentKey)
if sshErr != nil {
return sshErr
}
}

cmds = append(cmds, commandBuild(p.Build)) // docker build
Expand Down Expand Up @@ -344,8 +340,8 @@ func commandBuild(build Build) *exec.Cmd {
if build.Platform != "" {
args = append(args, "--platform", build.Platform)
}
for _, sshagent := range build.SSHAgent {
args = append(args, "--ssh", sshagent)
if build.SSHKeyPath != "" {
args = append(args, "--ssh", build.SSHKeyPath)
}

if build.AutoLabel {
Expand Down Expand Up @@ -373,7 +369,7 @@ func commandBuild(build Build) *exec.Cmd {
}

// we need to enable buildkit, for secret support and ssh agent support
if build.Secret != "" || len(build.SecretEnvs) > 0 || len(build.SecretFiles) > 0 || len(build.SSHAgent) > 0 {
if build.Secret != "" || len(build.SecretEnvs) > 0 || len(build.SecretFiles) > 0 || build.SSHAgentKey != "" {
os.Setenv("DOCKER_BUILDKIT", "1")
}
return exec.Command(dockerExe, args...)
Expand Down Expand Up @@ -526,38 +522,25 @@ func commandRmi(tag string) *exec.Cmd {
return exec.Command(dockerExe, "rmi", tag)
}

func commandSSHAgentForwardingSetup(build Build) []*exec.Cmd {
cmds := make([]*exec.Cmd, 0)
if err := writeSSHPrivateKey(); err != nil {
log.Fatalf("unable to setup ssh agent forwarding: %s", err)
}
os.Setenv("SSH_AUTH_SOCK", SSHAgentSockPath)
cmds = append(cmds, exec.Command("ssh-agent", "-a", SSHAgentSockPath))
cmds = append(cmds, exec.Command("ssh-add"))
return cmds
}

func writeSSHPrivateKey() error {
privateKeyBase64 := os.Getenv(SSHPrivateKeyFromEnv)
if privateKeyBase64 == "" {
return fmt.Errorf("%s must be defined and contain the base64 encoded private key to use for ssh agent forwarding", SSHPrivateKeyFromEnv)
}
var err error
privateKey, err := base64.StdEncoding.DecodeString(privateKeyBase64)
if err != nil {
return fmt.Errorf("unable to base64 decode private key")
}
func writeSSHPrivateKey(key string) (path string, err error) {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("unable to determine home directory: %s", err)
return "", fmt.Errorf("unable to determine home directory: %s", err)
}
if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0700); err != nil {
return fmt.Errorf("unable to create .ssh directory: %s", err)
return "", fmt.Errorf("unable to create .ssh directory: %s", err)
}
if err := os.WriteFile(filepath.Join(home, ".ssh", "id_rsa"), privateKey, 0400); err != nil {
return fmt.Errorf("unable to write ssh key: %s", err)
privateKey, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return "", fmt.Errorf("unable to base64 decode private ssh key: %s", err)
}
return nil
pathToKey := filepath.Join(home, ".ssh", "id_rsa")
if err := os.WriteFile(pathToKey, privateKey, 0400); err != nil {
return "", fmt.Errorf("unable to write ssh key %s: %s", pathToKey, err)
}
path = fmt.Sprintf("default=%s", pathToKey)

return path, nil
}

// trace writes each command to stdout with the command wrapped in an xml
Expand Down
20 changes: 20 additions & 0 deletions docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,26 @@ func TestCommandBuild(t *testing.T) {
"test/platform",
),
},
{
name: "ssh agent",
build: Build{
Name: "plugins/drone-docker:latest",
Dockerfile: "Dockerfile",
Context: ".",
SSHKeyPath: "id_rsa=/root/.ssh/id_rsa",
},
want: exec.Command(
dockerExe,
"build",
"--rm=true",
"-f",
"Dockerfile",
"-t",
"plugins/drone-docker:latest",
".",
"--ssh id_rsa=/root/.ssh/id_rsa",
),
},
}

for _, tc := range tcs {
Expand Down

0 comments on commit a2f8157

Please sign in to comment.