github.com/goern/docker@v1.9.0-rc1/api/client/trust.go (about) 1 package client 2 3 import ( 4 "bufio" 5 "encoding/hex" 6 "encoding/json" 7 "errors" 8 "fmt" 9 "io" 10 "net" 11 "net/http" 12 "net/url" 13 "os" 14 "path/filepath" 15 "regexp" 16 "sort" 17 "strconv" 18 "time" 19 20 "github.com/Sirupsen/logrus" 21 "github.com/docker/distribution/digest" 22 "github.com/docker/distribution/registry/client/auth" 23 "github.com/docker/distribution/registry/client/transport" 24 "github.com/docker/docker/cliconfig" 25 "github.com/docker/docker/pkg/ansiescape" 26 "github.com/docker/docker/pkg/ioutils" 27 flag "github.com/docker/docker/pkg/mflag" 28 "github.com/docker/docker/pkg/tlsconfig" 29 "github.com/docker/docker/registry" 30 "github.com/docker/notary/client" 31 "github.com/docker/notary/pkg/passphrase" 32 "github.com/docker/notary/trustmanager" 33 "github.com/endophage/gotuf/data" 34 ) 35 36 var untrusted bool 37 38 func addTrustedFlags(fs *flag.FlagSet, verify bool) { 39 var trusted bool 40 if e := os.Getenv("DOCKER_CONTENT_TRUST"); e != "" { 41 if t, err := strconv.ParseBool(e); t || err != nil { 42 // treat any other value as true 43 trusted = true 44 } 45 } 46 message := "Skip image signing" 47 if verify { 48 message = "Skip image verification" 49 } 50 fs.BoolVar(&untrusted, []string{"-disable-content-trust"}, !trusted, message) 51 } 52 53 func isTrusted() bool { 54 return !untrusted 55 } 56 57 var targetRegexp = regexp.MustCompile(`([\S]+): digest: ([\S]+) size: ([\d]+)`) 58 59 type target struct { 60 reference registry.Reference 61 digest digest.Digest 62 size int64 63 } 64 65 func (cli *DockerCli) trustDirectory() string { 66 return filepath.Join(cliconfig.ConfigDir(), "trust") 67 } 68 69 // certificateDirectory returns the directory containing 70 // TLS certificates for the given server. An error is 71 // returned if there was an error parsing the server string. 72 func (cli *DockerCli) certificateDirectory(server string) (string, error) { 73 u, err := url.Parse(server) 74 if err != nil { 75 return "", err 76 } 77 78 return filepath.Join(cliconfig.ConfigDir(), "tls", u.Host), nil 79 } 80 81 func trustServer(index *registry.IndexInfo) (string, error) { 82 if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" { 83 urlObj, err := url.Parse(s) 84 if err != nil || urlObj.Scheme != "https" { 85 return "", fmt.Errorf("valid https URL required for trust server, got %s", s) 86 } 87 88 return s, nil 89 } 90 if index.Official { 91 return registry.NotaryServer, nil 92 } 93 return "https://" + index.Name, nil 94 } 95 96 type simpleCredentialStore struct { 97 auth cliconfig.AuthConfig 98 } 99 100 func (scs simpleCredentialStore) Basic(u *url.URL) (string, string) { 101 return scs.auth.Username, scs.auth.Password 102 } 103 104 func (cli *DockerCli) getNotaryRepository(repoInfo *registry.RepositoryInfo, authConfig cliconfig.AuthConfig) (*client.NotaryRepository, error) { 105 server, err := trustServer(repoInfo.Index) 106 if err != nil { 107 return nil, err 108 } 109 110 var cfg = tlsconfig.ClientDefault 111 cfg.InsecureSkipVerify = !repoInfo.Index.Secure 112 113 // Get certificate base directory 114 certDir, err := cli.certificateDirectory(server) 115 if err != nil { 116 return nil, err 117 } 118 logrus.Debugf("reading certificate directory: %s", certDir) 119 120 if err := registry.ReadCertsDirectory(&cfg, certDir); err != nil { 121 return nil, err 122 } 123 124 base := &http.Transport{ 125 Proxy: http.ProxyFromEnvironment, 126 Dial: (&net.Dialer{ 127 Timeout: 30 * time.Second, 128 KeepAlive: 30 * time.Second, 129 DualStack: true, 130 }).Dial, 131 TLSHandshakeTimeout: 10 * time.Second, 132 TLSClientConfig: &cfg, 133 DisableKeepAlives: true, 134 } 135 136 // Skip configuration headers since request is not going to Docker daemon 137 modifiers := registry.DockerHeaders(http.Header{}) 138 authTransport := transport.NewTransport(base, modifiers...) 139 pingClient := &http.Client{ 140 Transport: authTransport, 141 Timeout: 5 * time.Second, 142 } 143 endpointStr := server + "/v2/" 144 req, err := http.NewRequest("GET", endpointStr, nil) 145 if err != nil { 146 return nil, err 147 } 148 149 challengeManager := auth.NewSimpleChallengeManager() 150 151 resp, err := pingClient.Do(req) 152 if err != nil { 153 // Ignore error on ping to operate in offline mode 154 logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err) 155 } else { 156 defer resp.Body.Close() 157 158 // Add response to the challenge manager to parse out 159 // authentication header and register authentication method 160 if err := challengeManager.AddResponse(resp); err != nil { 161 return nil, err 162 } 163 } 164 165 creds := simpleCredentialStore{auth: authConfig} 166 tokenHandler := auth.NewTokenHandler(authTransport, creds, repoInfo.CanonicalName, "push", "pull") 167 basicHandler := auth.NewBasicHandler(creds) 168 modifiers = append(modifiers, transport.RequestModifier(auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))) 169 tr := transport.NewTransport(base, modifiers...) 170 171 return client.NewNotaryRepository(cli.trustDirectory(), repoInfo.CanonicalName, server, tr, cli.getPassphraseRetriever()) 172 } 173 174 func convertTarget(t client.Target) (target, error) { 175 h, ok := t.Hashes["sha256"] 176 if !ok { 177 return target{}, errors.New("no valid hash, expecting sha256") 178 } 179 return target{ 180 reference: registry.ParseReference(t.Name), 181 digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)), 182 size: t.Length, 183 }, nil 184 } 185 186 func (cli *DockerCli) getPassphraseRetriever() passphrase.Retriever { 187 aliasMap := map[string]string{ 188 "root": "root", 189 "snapshot": "repository", 190 "targets": "repository", 191 } 192 baseRetriever := passphrase.PromptRetrieverWithInOut(cli.in, cli.out, aliasMap) 193 env := map[string]string{ 194 "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"), 195 "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), 196 "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), 197 } 198 199 // Backwards compatibility with old env names. We should remove this in 1.10 200 if env["root"] == "" { 201 env["root"] = os.Getenv("DOCKER_CONTENT_TRUST_OFFLINE_PASSPHRASE") 202 fmt.Fprintf(cli.err, "[DEPRECATED] The environment variable DOCKER_CONTENT_TRUST_OFFLINE_PASSPHRASE has been deprecated and will be removed in v1.10. Please use DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE\n") 203 204 } 205 if env["snapshot"] == "" || env["targets"] == "" { 206 env["snapshot"] = os.Getenv("DOCKER_CONTENT_TRUST_TAGGING_PASSPHRASE") 207 env["targets"] = os.Getenv("DOCKER_CONTENT_TRUST_TAGGING_PASSPHRASE") 208 fmt.Fprintf(cli.err, "[DEPRECATED] The environment variable DOCKER_CONTENT_TRUST_TAGGING_PASSPHRASE has been deprecated and will be removed in v1.10. Please use DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE\n") 209 210 } 211 212 return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) { 213 if v := env[alias]; v != "" { 214 return v, numAttempts > 1, nil 215 } 216 return baseRetriever(keyName, alias, createNew, numAttempts) 217 } 218 } 219 220 func (cli *DockerCli) trustedReference(repo string, ref registry.Reference) (registry.Reference, error) { 221 repoInfo, err := registry.ParseRepositoryInfo(repo) 222 if err != nil { 223 return nil, err 224 } 225 226 // Resolve the Auth config relevant for this server 227 authConfig := registry.ResolveAuthConfig(cli.configFile, repoInfo.Index) 228 229 notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig) 230 if err != nil { 231 fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err) 232 return nil, err 233 } 234 235 t, err := notaryRepo.GetTargetByName(ref.String()) 236 if err != nil { 237 return nil, err 238 } 239 r, err := convertTarget(*t) 240 if err != nil { 241 return nil, err 242 243 } 244 245 return registry.DigestReference(r.digest), nil 246 } 247 248 func (cli *DockerCli) tagTrusted(repoInfo *registry.RepositoryInfo, trustedRef, ref registry.Reference) error { 249 fullName := trustedRef.ImageName(repoInfo.LocalName) 250 fmt.Fprintf(cli.out, "Tagging %s as %s\n", fullName, ref.ImageName(repoInfo.LocalName)) 251 tv := url.Values{} 252 tv.Set("repo", repoInfo.LocalName) 253 tv.Set("tag", ref.String()) 254 tv.Set("force", "1") 255 256 if _, _, err := readBody(cli.call("POST", "/images/"+fullName+"/tag?"+tv.Encode(), nil, nil)); err != nil { 257 return err 258 } 259 260 return nil 261 } 262 263 func notaryError(err error) error { 264 switch err.(type) { 265 case *json.SyntaxError: 266 logrus.Debugf("Notary syntax error: %s", err) 267 return errors.New("no trust data available for remote repository") 268 case client.ErrExpired: 269 return fmt.Errorf("remote repository out-of-date: %v", err) 270 case trustmanager.ErrKeyNotFound: 271 return fmt.Errorf("signing keys not found: %v", err) 272 case *net.OpError: 273 return fmt.Errorf("error contacting notary server: %v", err) 274 } 275 276 return err 277 } 278 279 func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig cliconfig.AuthConfig) error { 280 var ( 281 v = url.Values{} 282 refs = []target{} 283 ) 284 285 notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig) 286 if err != nil { 287 fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err) 288 return err 289 } 290 291 if ref.String() == "" { 292 // List all targets 293 targets, err := notaryRepo.ListTargets() 294 if err != nil { 295 return notaryError(err) 296 } 297 for _, tgt := range targets { 298 t, err := convertTarget(*tgt) 299 if err != nil { 300 fmt.Fprintf(cli.out, "Skipping target for %q\n", repoInfo.LocalName) 301 continue 302 } 303 refs = append(refs, t) 304 } 305 } else { 306 t, err := notaryRepo.GetTargetByName(ref.String()) 307 if err != nil { 308 return notaryError(err) 309 } 310 r, err := convertTarget(*t) 311 if err != nil { 312 return err 313 314 } 315 refs = append(refs, r) 316 } 317 318 v.Set("fromImage", repoInfo.LocalName) 319 for i, r := range refs { 320 displayTag := r.reference.String() 321 if displayTag != "" { 322 displayTag = ":" + displayTag 323 } 324 fmt.Fprintf(cli.out, "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), repoInfo.LocalName, displayTag, r.digest) 325 v.Set("tag", r.digest.String()) 326 327 _, _, err = cli.clientRequestAttemptLogin("POST", "/images/create?"+v.Encode(), nil, cli.out, repoInfo.Index, "pull") 328 if err != nil { 329 return err 330 } 331 332 // If reference is not trusted, tag by trusted reference 333 if !r.reference.HasDigest() { 334 if err := cli.tagTrusted(repoInfo, registry.DigestReference(r.digest), r.reference); err != nil { 335 return err 336 337 } 338 } 339 } 340 return nil 341 } 342 343 func selectKey(keys map[string]string) string { 344 if len(keys) == 0 { 345 return "" 346 } 347 348 keyIDs := []string{} 349 for k := range keys { 350 keyIDs = append(keyIDs, k) 351 } 352 353 // TODO(dmcgowan): let user choose if multiple keys, now pick consistently 354 sort.Strings(keyIDs) 355 356 return keyIDs[0] 357 } 358 359 func targetStream(in io.Writer) (io.WriteCloser, <-chan []target) { 360 r, w := io.Pipe() 361 out := io.MultiWriter(in, w) 362 targetChan := make(chan []target) 363 364 go func() { 365 targets := []target{} 366 scanner := bufio.NewScanner(r) 367 scanner.Split(ansiescape.ScanANSILines) 368 for scanner.Scan() { 369 line := scanner.Bytes() 370 if matches := targetRegexp.FindSubmatch(line); len(matches) == 4 { 371 dgst, err := digest.ParseDigest(string(matches[2])) 372 if err != nil { 373 // Line does match what is expected, continue looking for valid lines 374 logrus.Debugf("Bad digest value %q in matched line, ignoring\n", string(matches[2])) 375 continue 376 } 377 s, err := strconv.ParseInt(string(matches[3]), 10, 64) 378 if err != nil { 379 // Line does match what is expected, continue looking for valid lines 380 logrus.Debugf("Bad size value %q in matched line, ignoring\n", string(matches[3])) 381 continue 382 } 383 384 targets = append(targets, target{ 385 reference: registry.ParseReference(string(matches[1])), 386 digest: dgst, 387 size: s, 388 }) 389 } 390 } 391 targetChan <- targets 392 }() 393 394 return ioutils.NewWriteCloserWrapper(out, w.Close), targetChan 395 } 396 397 func (cli *DockerCli) trustedPush(repoInfo *registry.RepositoryInfo, tag string, authConfig cliconfig.AuthConfig) error { 398 streamOut, targetChan := targetStream(cli.out) 399 400 v := url.Values{} 401 v.Set("tag", tag) 402 403 _, _, err := cli.clientRequestAttemptLogin("POST", "/images/"+repoInfo.LocalName+"/push?"+v.Encode(), nil, streamOut, repoInfo.Index, "push") 404 // Close stream channel to finish target parsing 405 if err := streamOut.Close(); err != nil { 406 return err 407 } 408 // Check error from request 409 if err != nil { 410 return err 411 } 412 413 // Get target results 414 targets := <-targetChan 415 416 if tag == "" { 417 fmt.Fprintf(cli.out, "No tag specified, skipping trust metadata push\n") 418 return nil 419 } 420 if len(targets) == 0 { 421 fmt.Fprintf(cli.out, "No targets found, skipping trust metadata push\n") 422 return nil 423 } 424 425 fmt.Fprintf(cli.out, "Signing and pushing trust metadata\n") 426 427 repo, err := cli.getNotaryRepository(repoInfo, authConfig) 428 if err != nil { 429 fmt.Fprintf(cli.out, "Error establishing connection to notary repository: %s\n", err) 430 return err 431 } 432 433 for _, target := range targets { 434 h, err := hex.DecodeString(target.digest.Hex()) 435 if err != nil { 436 return err 437 } 438 t := &client.Target{ 439 Name: target.reference.String(), 440 Hashes: data.Hashes{ 441 string(target.digest.Algorithm()): h, 442 }, 443 Length: int64(target.size), 444 } 445 if err := repo.AddTarget(t); err != nil { 446 return err 447 } 448 } 449 450 err = repo.Publish() 451 if _, ok := err.(*client.ErrRepoNotInitialized); !ok { 452 return notaryError(err) 453 } 454 455 ks := repo.KeyStoreManager 456 keys := ks.RootKeyStore().ListKeys() 457 458 rootKey := selectKey(keys) 459 if rootKey == "" { 460 rootKey, err = ks.GenRootKey("ecdsa") 461 if err != nil { 462 return err 463 } 464 } 465 466 cryptoService, err := ks.GetRootCryptoService(rootKey) 467 if err != nil { 468 return err 469 } 470 471 if err := repo.Initialize(cryptoService); err != nil { 472 return notaryError(err) 473 } 474 fmt.Fprintf(cli.out, "Finished initializing %q\n", repoInfo.CanonicalName) 475 476 return notaryError(repo.Publish()) 477 }