/
connection.go
239 lines (207 loc) · 6.09 KB
/
connection.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package docker
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/docker/cli/opts"
"github.com/docker/docker/client"
"github.com/docker/go-connections/sockets"
"github.com/kevinburke/ssh_config"
homedir "github.com/mitchellh/go-homedir"
drytls "github.com/moncho/dry/tls"
"github.com/moncho/dry/version"
"golang.org/x/crypto/ssh"
)
const (
//DefaultConnectionTimeout is the timeout for connecting with the Docker daemon
DefaultConnectionTimeout = 32 * time.Second
)
var defaultDockerPath string
var headers = map[string]string{
"User-Agent": "dry/" + version.VERSION,
}
func init() {
defaultDockerPath, _ = homedir.Expand("~/.docker")
}
func connect(client client.APIClient, env Env) (*DockerDaemon, error) {
store, err := NewDockerContainerStore(client)
if err != nil {
return nil, err
}
d := &DockerDaemon{
client: client,
err: err,
s: store,
dockerEnv: env,
resolver: newResolver(client, false),
}
if err := d.init(); err != nil {
return nil, err
}
return d, nil
}
func getServerHost(env Env) (string, error) {
host := env.DockerHost
if host == "" {
host = DefaultDockerHost
}
return opts.ParseHost(env.DockerCertPath != "", host)
}
func newHTTPClient(host string, config *tls.Config) (*http.Client, error) {
if config == nil {
// let the api client configure the default transport.
return nil, nil
}
url, err := client.ParseHostURL(host)
if err != nil {
return nil, err
}
transport := &http.Transport{
TLSClientConfig: config,
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(url.Scheme, url.Host, DefaultConnectionTimeout)
},
}
if err = sockets.ConfigureTransport(transport, url.Scheme, url.Host); err != nil {
return nil, err
}
return &http.Client{
Transport: transport,
CheckRedirect: client.CheckRedirect,
}, nil
}
// ConnectToDaemon connects to a Docker daemon using the given properties.
func ConnectToDaemon(env Env) (*DockerDaemon, error) {
host, err := getServerHost(env)
if err != nil {
return nil, fmt.Errorf("invalid host: %w", err)
}
var options *drytls.Options
//If a path to certificates is given use the path to read certificates from
if dockerCertPath := env.DockerCertPath; dockerCertPath != "" {
options = &drytls.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
InsecureSkipVerify: env.DockerTLSVerify,
}
} else if env.DockerTLSVerify {
//No cert path is given but TLS verify is set, default location for
//docker certs will be used.
//See https://docs.docker.com/engine/security/https/#secure-by-default
//Fixes #23
options = &drytls.Options{
CAFile: filepath.Join(defaultDockerPath, "ca.pem"),
CertFile: filepath.Join(defaultDockerPath, "cert.pem"),
KeyFile: filepath.Join(defaultDockerPath, "key.pem"),
InsecureSkipVerify: env.DockerTLSVerify,
}
env.DockerCertPath = defaultDockerPath
}
var opt []client.Opt
if options != nil {
opt = append(opt, client.WithTLSClientConfig(options.CAFile, options.CertFile, options.KeyFile))
}
if host != "" && strings.Index(host, "ssh") == 0 {
//if it starts with ssh, its an ssh connection, and we need to handle this specially
//github.com/docker/docker does not handle ssh, as an upgrade to go-connections need to be made
//see https://github.com/docker/go-connections/pull/39
url, err := url.Parse(host)
if err != nil {
return nil, err
}
pass, _ := url.User.Password()
sshConfig, err := configureSshTransport(url.Host, url.User.Username(), pass)
if err != nil {
return nil, err
}
opt = append(opt, client.WithDialContext(
func(ctx context.Context, network, addr string) (net.Conn, error) {
return connectSshTransport(url.Host, url.Path, sshConfig)
}))
} else if host != "" {
//default uses the docker library to connect to hosts
opt = append(opt, client.WithHost(host))
}
client, err := client.NewClientWithOpts(opt...)
if err != nil {
return nil, fmt.Errorf("create Docker client: %w", err)
}
return connect(client, env)
}
func configureSshTransport(host string, user string, pass string) (*ssh.ClientConfig, error) {
dirname, err := homedir.Dir()
if err != nil {
return nil, err
}
var methods []ssh.AuthMethod
foundIdentityFile := false
files := ssh_config.GetAll(host, "IdentityFile")
for _, v := range files {
//see https://github.com/docker/go-connections/pull/39#issuecomment-312765226
if _, err := os.Stat(v); err == nil {
methods, err = readPk(v, methods, dirname)
if err != nil {
return nil, err
}
foundIdentityFile = true
}
}
if !foundIdentityFile {
pkFilenames, err := os.ReadDir(dirname + "/.ssh/")
if err != nil {
return nil, err
}
for _, pkFilename := range pkFilenames {
if strings.Index(pkFilename.Name(), "id_") == 0 && !strings.HasSuffix(pkFilename.Name(), ".pub") {
methods, err = readPk(pkFilename.Name(), methods, dirname+"/.ssh/")
if err != nil {
return nil, err
}
}
}
}
if pass != "" {
methods = append(methods, []ssh.AuthMethod{ssh.Password(pass)}...)
}
return &ssh.ClientConfig{
User: user,
Auth: methods,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}, nil
}
func readPk(pkFilename string, auth []ssh.AuthMethod, dirname string) ([]ssh.AuthMethod, error) {
pk, err := os.ReadFile(dirname + pkFilename)
if err != nil {
return nil, nil
}
signer, err := ssh.ParsePrivateKey(pk)
if err != nil {
return nil, err
}
auth = append(auth, []ssh.AuthMethod{ssh.PublicKeys(signer)}...)
return auth, nil
}
func connectSshTransport(host string, path string, sshConfig *ssh.ClientConfig) (net.Conn, error) {
remoteConn, err := net.Dial("tcp", host)
if err != nil {
return nil, err
}
ncc, chans, reqs, err := ssh.NewClientConn(remoteConn, "", sshConfig)
if err != nil {
return nil, err
}
sClient := ssh.NewClient(ncc, chans, reqs)
c, err := sClient.Dial("unix", path)
if err != nil {
return nil, err
}
return c, nil
}