1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package git
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus"
"gitlab.com/gitlab-org/gitaly/v15/internal/helper/perm"
)
// BuildSSHInvocation builds a command line to invoke SSH with the provided key and known hosts.
// Both are optional.
func BuildSSHInvocation(ctx context.Context, sshKey, knownHosts string) (string, func(), error) {
const sshCommand = "ssh"
if sshKey == "" && knownHosts == "" {
return sshCommand, func() {}, nil
}
tmpDir, err := os.MkdirTemp("", "gitaly-ssh-invocation")
if err != nil {
return "", func() {}, fmt.Errorf("create temporary directory: %w", err)
}
cleanup := func() {
if err := os.RemoveAll(tmpDir); err != nil {
ctxlogrus.Extract(ctx).WithError(err).Error("failed to remove tmp directory with ssh key/config")
}
}
args := []string{sshCommand}
if sshKey != "" {
sshKeyFile := filepath.Join(tmpDir, "ssh-key")
if err := os.WriteFile(sshKeyFile, []byte(sshKey), perm.PrivateWriteOnceFile); err != nil {
cleanup()
return "", nil, fmt.Errorf("create ssh key file: %w", err)
}
args = append(args, "-oIdentitiesOnly=yes", "-oIdentityFile="+sshKeyFile)
}
if knownHosts != "" {
knownHostsFile := filepath.Join(tmpDir, "known-hosts")
if err := os.WriteFile(knownHostsFile, []byte(knownHosts), perm.PrivateWriteOnceFile); err != nil {
cleanup()
return "", nil, fmt.Errorf("create known hosts file: %w", err)
}
args = append(args, "-oStrictHostKeyChecking=yes", "-oCheckHostIP=no", "-oUserKnownHostsFile="+knownHostsFile)
}
return strings.Join(args, " "), cleanup, nil
}
|