This repository has been archived by the owner on Sep 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathhost.go
287 lines (232 loc) · 6.24 KB
/
host.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"time"
log "github.com/Sirupsen/logrus"
"github.com/docker/libtrust"
"github.com/docker/machine/drivers"
)
var (
validHostNameChars = `[a-zA-Z0-9_]`
validHostNamePattern = regexp.MustCompile(`^` + validHostNameChars + `+$`)
)
type Host struct {
Name string `json:"-"`
DriverName string
Driver drivers.Driver
storePath string
}
type hostConfig struct {
DriverName string
}
func NewHost(name, driverName, storePath string) (*Host, error) {
driver, err := drivers.NewDriver(driverName, storePath)
if err != nil {
return nil, err
}
return &Host{
Name: name,
DriverName: driverName,
Driver: driver,
storePath: storePath,
}, nil
}
func LoadHost(name string, storePath string) (*Host, error) {
if _, err := os.Stat(storePath); os.IsNotExist(err) {
return nil, fmt.Errorf("Host %q does not exist", name)
}
host := &Host{Name: name, storePath: storePath}
if err := host.LoadConfig(); err != nil {
return nil, err
}
return host, nil
}
func ValidateHostName(name string) (string, error) {
if !validHostNamePattern.MatchString(name) {
return name, fmt.Errorf("Invalid host name %q, it must match %s", name, validHostNamePattern)
}
return name, nil
}
func loadTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {
if err := os.MkdirAll(filepath.Dir(trustKeyPath), 0700); err != nil {
return nil, err
}
trustKey, err := libtrust.LoadKeyFile(trustKeyPath)
if err == libtrust.ErrKeyFileDoesNotExist {
trustKey, err = libtrust.GenerateECP256PrivateKey()
if err != nil {
return nil, fmt.Errorf("error generating key: %s", err)
}
if err := libtrust.SaveKey(trustKeyPath, trustKey); err != nil {
return nil, fmt.Errorf("error saving key file: %s", err)
}
dir, file := filepath.Split(trustKeyPath)
if err := libtrust.SavePublicKey(filepath.Join(dir, "public-"+file), trustKey.PublicKey()); err != nil {
return nil, fmt.Errorf("error saving public key file: %s", err)
}
} else if err != nil {
return nil, fmt.Errorf("error loading key file: %s", err)
}
return trustKey, nil
}
func (h *Host) addHostToKnownHosts() error {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS10,
}
trustKeyPath := filepath.Join(drivers.GetDockerDir(), "key.json")
knownHostsPath := filepath.Join(drivers.GetDockerDir(), "known-hosts.json")
driverUrl, err := h.GetURL()
if err != nil {
return fmt.Errorf("unable to get machine url: %s", err)
}
u, err := url.Parse(driverUrl)
if err != nil {
return fmt.Errorf("unable to parse machine url")
}
if u.Scheme == "unix" {
return nil
}
addr := u.Host
proto := "tcp"
trustKey, err := loadTrustKey(trustKeyPath)
if err != nil {
return fmt.Errorf("unable to load trust key: %s", err)
}
knownHosts, err := libtrust.LoadKeySetFile(knownHostsPath)
if err != nil {
return fmt.Errorf("could not load trusted hosts file: %s", err)
}
allowedHosts, err := libtrust.FilterByHosts(knownHosts, addr, false)
if err != nil {
return fmt.Errorf("error filtering hosts: %s", err)
}
certPool, err := libtrust.GenerateCACertPool(trustKey, allowedHosts)
if err != nil {
return fmt.Errorf("Could not create CA pool: %s", err)
}
tlsConfig.ServerName = "docker"
tlsConfig.RootCAs = certPool
x509Cert, err := libtrust.GenerateSelfSignedClientCert(trustKey)
if err != nil {
return fmt.Errorf("certificate generation error: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{{
Certificate: [][]byte{x509Cert.Raw},
PrivateKey: trustKey.CryptoPrivateKey(),
Leaf: x509Cert,
}}
tlsConfig.InsecureSkipVerify = true
testConn, err := tls.Dial(proto, addr, tlsConfig)
if err != nil {
return fmt.Errorf("tls Handshake error: %s", err)
}
opts := x509.VerifyOptions{
Roots: tlsConfig.RootCAs,
CurrentTime: time.Now(),
DNSName: tlsConfig.ServerName,
Intermediates: x509.NewCertPool(),
}
certs := testConn.ConnectionState().PeerCertificates
for i, cert := range certs {
if i == 0 {
continue
}
opts.Intermediates.AddCert(cert)
}
if _, err := certs[0].Verify(opts); err != nil {
if _, ok := err.(x509.UnknownAuthorityError); ok {
pubKey, err := libtrust.FromCryptoPublicKey(certs[0].PublicKey)
if err != nil {
return fmt.Errorf("error extracting public key from cert: %s", err)
}
pubKey.AddExtendedField("hosts", []string{addr})
log.Debugf("Adding machine to known hosts: %s", addr)
if err := libtrust.AddKeySetFile(knownHostsPath, pubKey); err != nil {
return fmt.Errorf("error adding machine to known hosts: %s", err)
}
}
}
testConn.Close()
return nil
}
func (h *Host) Create() error {
if err := h.Driver.Create(); err != nil {
return err
}
if err := h.SaveConfig(); err != nil {
return err
}
if err := h.addHostToKnownHosts(); err != nil {
return err
}
return nil
}
func (h *Host) Start() error {
return h.Driver.Start()
}
func (h *Host) Stop() error {
return h.Driver.Stop()
}
func (h *Host) Upgrade() error {
return h.Driver.Upgrade()
}
func (h *Host) Remove(force bool) error {
if err := h.Driver.Remove(); err != nil {
if !force {
return err
}
}
return h.removeStorePath()
}
func (h *Host) removeStorePath() error {
file, err := os.Stat(h.storePath)
if err != nil {
return err
}
if !file.IsDir() {
return fmt.Errorf("%q is not a directory", h.storePath)
}
return os.RemoveAll(h.storePath)
}
func (h *Host) GetURL() (string, error) {
return h.Driver.GetURL()
}
func (h *Host) LoadConfig() error {
data, err := ioutil.ReadFile(filepath.Join(h.storePath, "config.json"))
if err != nil {
return err
}
// First pass: find the driver name and load the driver
var config hostConfig
if err := json.Unmarshal(data, &config); err != nil {
return err
}
driver, err := drivers.NewDriver(config.DriverName, h.storePath)
if err != nil {
return err
}
h.Driver = driver
// Second pass: unmarshal driver config into correct driver
if err := json.Unmarshal(data, &h); err != nil {
return err
}
return nil
}
func (h *Host) SaveConfig() error {
data, err := json.Marshal(h)
if err != nil {
return err
}
if err := ioutil.WriteFile(filepath.Join(h.storePath, "config.json"), data, 0600); err != nil {
return err
}
return nil
}