trust.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package client
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "sort"
  14. "strconv"
  15. "time"
  16. "golang.org/x/net/context"
  17. "github.com/Sirupsen/logrus"
  18. "github.com/docker/distribution/digest"
  19. "github.com/docker/distribution/registry/client/auth"
  20. "github.com/docker/distribution/registry/client/transport"
  21. "github.com/docker/docker/cliconfig"
  22. "github.com/docker/docker/distribution"
  23. "github.com/docker/docker/pkg/jsonmessage"
  24. flag "github.com/docker/docker/pkg/mflag"
  25. "github.com/docker/docker/reference"
  26. "github.com/docker/docker/registry"
  27. apiclient "github.com/docker/engine-api/client"
  28. "github.com/docker/engine-api/types"
  29. registrytypes "github.com/docker/engine-api/types/registry"
  30. "github.com/docker/go-connections/tlsconfig"
  31. "github.com/docker/notary/client"
  32. "github.com/docker/notary/passphrase"
  33. "github.com/docker/notary/trustmanager"
  34. "github.com/docker/notary/tuf/data"
  35. "github.com/docker/notary/tuf/signed"
  36. "github.com/docker/notary/tuf/store"
  37. )
  38. var (
  39. releasesRole = path.Join(data.CanonicalTargetsRole, "releases")
  40. untrusted bool
  41. )
  42. func addTrustedFlags(fs *flag.FlagSet, verify bool) {
  43. var trusted bool
  44. if e := os.Getenv("DOCKER_CONTENT_TRUST"); e != "" {
  45. if t, err := strconv.ParseBool(e); t || err != nil {
  46. // treat any other value as true
  47. trusted = true
  48. }
  49. }
  50. message := "Skip image signing"
  51. if verify {
  52. message = "Skip image verification"
  53. }
  54. fs.BoolVar(&untrusted, []string{"-disable-content-trust"}, !trusted, message)
  55. }
  56. func isTrusted() bool {
  57. return !untrusted
  58. }
  59. type target struct {
  60. reference registry.Reference
  61. digest digest.Digest
  62. size int64
  63. }
  64. func (cli *DockerCli) trustDirectory() string {
  65. return filepath.Join(cliconfig.ConfigDir(), "trust")
  66. }
  67. // certificateDirectory returns the directory containing
  68. // TLS certificates for the given server. An error is
  69. // returned if there was an error parsing the server string.
  70. func (cli *DockerCli) certificateDirectory(server string) (string, error) {
  71. u, err := url.Parse(server)
  72. if err != nil {
  73. return "", err
  74. }
  75. return filepath.Join(cliconfig.ConfigDir(), "tls", u.Host), nil
  76. }
  77. func trustServer(index *registrytypes.IndexInfo) (string, error) {
  78. if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" {
  79. urlObj, err := url.Parse(s)
  80. if err != nil || urlObj.Scheme != "https" {
  81. return "", fmt.Errorf("valid https URL required for trust server, got %s", s)
  82. }
  83. return s, nil
  84. }
  85. if index.Official {
  86. return registry.NotaryServer, nil
  87. }
  88. return "https://" + index.Name, nil
  89. }
  90. type simpleCredentialStore struct {
  91. auth types.AuthConfig
  92. }
  93. func (scs simpleCredentialStore) Basic(u *url.URL) (string, string) {
  94. return scs.auth.Username, scs.auth.Password
  95. }
  96. func (scs simpleCredentialStore) RefreshToken(u *url.URL, service string) string {
  97. return scs.auth.IdentityToken
  98. }
  99. func (scs simpleCredentialStore) SetRefreshToken(*url.URL, string, string) {
  100. }
  101. // getNotaryRepository returns a NotaryRepository which stores all the
  102. // information needed to operate on a notary repository.
  103. // It creates a HTTP transport providing authentication support.
  104. func (cli *DockerCli) getNotaryRepository(repoInfo *registry.RepositoryInfo, authConfig types.AuthConfig, actions ...string) (*client.NotaryRepository, error) {
  105. server, err := trustServer(repoInfo.Index)
  106. if err != nil {
  107. return nil, err
  108. }
  109. var cfg = tlsconfig.ClientDefault
  110. cfg.InsecureSkipVerify = !repoInfo.Index.Secure
  111. // Get certificate base directory
  112. certDir, err := cli.certificateDirectory(server)
  113. if err != nil {
  114. return nil, err
  115. }
  116. logrus.Debugf("reading certificate directory: %s", certDir)
  117. if err := registry.ReadCertsDirectory(&cfg, certDir); err != nil {
  118. return nil, err
  119. }
  120. base := &http.Transport{
  121. Proxy: http.ProxyFromEnvironment,
  122. Dial: (&net.Dialer{
  123. Timeout: 30 * time.Second,
  124. KeepAlive: 30 * time.Second,
  125. DualStack: true,
  126. }).Dial,
  127. TLSHandshakeTimeout: 10 * time.Second,
  128. TLSClientConfig: &cfg,
  129. DisableKeepAlives: true,
  130. }
  131. // Skip configuration headers since request is not going to Docker daemon
  132. modifiers := registry.DockerHeaders(clientUserAgent(), http.Header{})
  133. authTransport := transport.NewTransport(base, modifiers...)
  134. pingClient := &http.Client{
  135. Transport: authTransport,
  136. Timeout: 5 * time.Second,
  137. }
  138. endpointStr := server + "/v2/"
  139. req, err := http.NewRequest("GET", endpointStr, nil)
  140. if err != nil {
  141. return nil, err
  142. }
  143. challengeManager := auth.NewSimpleChallengeManager()
  144. resp, err := pingClient.Do(req)
  145. if err != nil {
  146. // Ignore error on ping to operate in offline mode
  147. logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err)
  148. } else {
  149. defer resp.Body.Close()
  150. // Add response to the challenge manager to parse out
  151. // authentication header and register authentication method
  152. if err := challengeManager.AddResponse(resp); err != nil {
  153. return nil, err
  154. }
  155. }
  156. creds := simpleCredentialStore{auth: authConfig}
  157. tokenHandler := auth.NewTokenHandler(authTransport, creds, repoInfo.FullName(), actions...)
  158. basicHandler := auth.NewBasicHandler(creds)
  159. modifiers = append(modifiers, transport.RequestModifier(auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)))
  160. tr := transport.NewTransport(base, modifiers...)
  161. return client.NewNotaryRepository(cli.trustDirectory(), repoInfo.FullName(), server, tr, cli.getPassphraseRetriever())
  162. }
  163. func convertTarget(t client.Target) (target, error) {
  164. h, ok := t.Hashes["sha256"]
  165. if !ok {
  166. return target{}, errors.New("no valid hash, expecting sha256")
  167. }
  168. return target{
  169. reference: registry.ParseReference(t.Name),
  170. digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)),
  171. size: t.Length,
  172. }, nil
  173. }
  174. func (cli *DockerCli) getPassphraseRetriever() passphrase.Retriever {
  175. aliasMap := map[string]string{
  176. "root": "root",
  177. "snapshot": "repository",
  178. "targets": "repository",
  179. "default": "repository",
  180. }
  181. baseRetriever := passphrase.PromptRetrieverWithInOut(cli.in, cli.out, aliasMap)
  182. env := map[string]string{
  183. "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"),
  184. "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  185. "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  186. "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  187. }
  188. // Backwards compatibility with old env names. We should remove this in 1.10
  189. if env["root"] == "" {
  190. if passphrase := os.Getenv("DOCKER_CONTENT_TRUST_OFFLINE_PASSPHRASE"); passphrase != "" {
  191. env["root"] = passphrase
  192. 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")
  193. }
  194. }
  195. if env["snapshot"] == "" || env["targets"] == "" || env["default"] == "" {
  196. if passphrase := os.Getenv("DOCKER_CONTENT_TRUST_TAGGING_PASSPHRASE"); passphrase != "" {
  197. env["snapshot"] = passphrase
  198. env["targets"] = passphrase
  199. env["default"] = passphrase
  200. 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")
  201. }
  202. }
  203. return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) {
  204. if v := env[alias]; v != "" {
  205. return v, numAttempts > 1, nil
  206. }
  207. // For non-root roles, we can also try the "default" alias if it is specified
  208. if v := env["default"]; v != "" && alias != data.CanonicalRootRole {
  209. return v, numAttempts > 1, nil
  210. }
  211. return baseRetriever(keyName, alias, createNew, numAttempts)
  212. }
  213. }
  214. func (cli *DockerCli) trustedReference(ref reference.NamedTagged) (reference.Canonical, error) {
  215. repoInfo, err := registry.ParseRepositoryInfo(ref)
  216. if err != nil {
  217. return nil, err
  218. }
  219. // Resolve the Auth config relevant for this server
  220. authConfig := cli.resolveAuthConfig(repoInfo.Index)
  221. notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig, "pull")
  222. if err != nil {
  223. fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err)
  224. return nil, err
  225. }
  226. t, err := notaryRepo.GetTargetByName(ref.Tag(), releasesRole, data.CanonicalTargetsRole)
  227. if err != nil {
  228. return nil, err
  229. }
  230. // Only list tags in the top level targets role or the releases delegation role - ignore
  231. // all other delegation roles
  232. if t.Role != releasesRole && t.Role != data.CanonicalTargetsRole {
  233. return nil, notaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.Tag()))
  234. }
  235. r, err := convertTarget(t.Target)
  236. if err != nil {
  237. return nil, err
  238. }
  239. return reference.WithDigest(ref, r.digest)
  240. }
  241. func (cli *DockerCli) tagTrusted(trustedRef reference.Canonical, ref reference.NamedTagged) error {
  242. fmt.Fprintf(cli.out, "Tagging %s as %s\n", trustedRef.String(), ref.String())
  243. options := types.ImageTagOptions{
  244. ImageID: trustedRef.String(),
  245. RepositoryName: trustedRef.Name(),
  246. Tag: ref.Tag(),
  247. Force: true,
  248. }
  249. return cli.client.ImageTag(context.Background(), options)
  250. }
  251. func notaryError(repoName string, err error) error {
  252. switch err.(type) {
  253. case *json.SyntaxError:
  254. logrus.Debugf("Notary syntax error: %s", err)
  255. return fmt.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName)
  256. case signed.ErrExpired:
  257. return fmt.Errorf("Error: remote repository %s out-of-date: %v", repoName, err)
  258. case trustmanager.ErrKeyNotFound:
  259. return fmt.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err)
  260. case *net.OpError:
  261. return fmt.Errorf("Error: error contacting notary server: %v", err)
  262. case store.ErrMetaNotFound:
  263. return fmt.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err)
  264. case signed.ErrInvalidKeyType:
  265. return fmt.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err)
  266. case signed.ErrNoKeys:
  267. return fmt.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err)
  268. case signed.ErrLowVersion:
  269. return fmt.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err)
  270. case signed.ErrRoleThreshold:
  271. return fmt.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err)
  272. case client.ErrRepositoryNotExist:
  273. return fmt.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err)
  274. case signed.ErrInsufficientSignatures:
  275. return fmt.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err)
  276. }
  277. return err
  278. }
  279. func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig types.AuthConfig, requestPrivilege apiclient.RequestPrivilegeFunc) error {
  280. var refs []target
  281. notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig, "pull")
  282. if err != nil {
  283. fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err)
  284. return err
  285. }
  286. if ref.String() == "" {
  287. // List all targets
  288. targets, err := notaryRepo.ListTargets(releasesRole, data.CanonicalTargetsRole)
  289. if err != nil {
  290. return notaryError(repoInfo.FullName(), err)
  291. }
  292. for _, tgt := range targets {
  293. t, err := convertTarget(tgt.Target)
  294. if err != nil {
  295. fmt.Fprintf(cli.out, "Skipping target for %q\n", repoInfo.Name())
  296. continue
  297. }
  298. // Only list tags in the top level targets role or the releases delegation role - ignore
  299. // all other delegation roles
  300. if tgt.Role != releasesRole && tgt.Role != data.CanonicalTargetsRole {
  301. continue
  302. }
  303. refs = append(refs, t)
  304. }
  305. if len(refs) == 0 {
  306. return notaryError(repoInfo.FullName(), fmt.Errorf("No trusted tags for %s", repoInfo.FullName()))
  307. }
  308. } else {
  309. t, err := notaryRepo.GetTargetByName(ref.String(), releasesRole, data.CanonicalTargetsRole)
  310. if err != nil {
  311. return notaryError(repoInfo.FullName(), err)
  312. }
  313. // Only get the tag if it's in the top level targets role or the releases delegation role
  314. // ignore it if it's in any other delegation roles
  315. if t.Role != releasesRole && t.Role != data.CanonicalTargetsRole {
  316. return notaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.String()))
  317. }
  318. logrus.Debugf("retrieving target for %s role\n", t.Role)
  319. r, err := convertTarget(t.Target)
  320. if err != nil {
  321. return err
  322. }
  323. refs = append(refs, r)
  324. }
  325. for i, r := range refs {
  326. displayTag := r.reference.String()
  327. if displayTag != "" {
  328. displayTag = ":" + displayTag
  329. }
  330. fmt.Fprintf(cli.out, "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), repoInfo.Name(), displayTag, r.digest)
  331. if err := cli.imagePullPrivileged(authConfig, repoInfo.Name(), r.digest.String(), requestPrivilege); err != nil {
  332. return err
  333. }
  334. // If reference is not trusted, tag by trusted reference
  335. if !r.reference.HasDigest() {
  336. tagged, err := reference.WithTag(repoInfo, r.reference.String())
  337. if err != nil {
  338. return err
  339. }
  340. trustedRef, err := reference.WithDigest(repoInfo, r.digest)
  341. if err != nil {
  342. return err
  343. }
  344. if err := cli.tagTrusted(trustedRef, tagged); err != nil {
  345. return err
  346. }
  347. }
  348. }
  349. return nil
  350. }
  351. func (cli *DockerCli) trustedPush(repoInfo *registry.RepositoryInfo, tag string, authConfig types.AuthConfig, requestPrivilege apiclient.RequestPrivilegeFunc) error {
  352. responseBody, err := cli.imagePushPrivileged(authConfig, repoInfo.Name(), tag, requestPrivilege)
  353. if err != nil {
  354. return err
  355. }
  356. defer responseBody.Close()
  357. // If it is a trusted push we would like to find the target entry which match the
  358. // tag provided in the function and then do an AddTarget later.
  359. target := &client.Target{}
  360. // Count the times of calling for handleTarget,
  361. // if it is called more that once, that should be considered an error in a trusted push.
  362. cnt := 0
  363. handleTarget := func(aux *json.RawMessage) {
  364. cnt++
  365. if cnt > 1 {
  366. // handleTarget should only be called one. This will be treated as an error.
  367. return
  368. }
  369. var pushResult distribution.PushResult
  370. err := json.Unmarshal(*aux, &pushResult)
  371. if err == nil && pushResult.Tag != "" && pushResult.Digest.Validate() == nil {
  372. h, err := hex.DecodeString(pushResult.Digest.Hex())
  373. if err != nil {
  374. target = nil
  375. return
  376. }
  377. target.Name = registry.ParseReference(pushResult.Tag).String()
  378. target.Hashes = data.Hashes{string(pushResult.Digest.Algorithm()): h}
  379. target.Length = int64(pushResult.Size)
  380. }
  381. }
  382. // We want trust signatures to always take an explicit tag,
  383. // otherwise it will act as an untrusted push.
  384. if tag == "" {
  385. if err = jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, nil); err != nil {
  386. return err
  387. }
  388. fmt.Fprintln(cli.out, "No tag specified, skipping trust metadata push")
  389. return nil
  390. }
  391. if err = jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, handleTarget); err != nil {
  392. return err
  393. }
  394. if cnt > 1 {
  395. return fmt.Errorf("internal error: only one call to handleTarget expected")
  396. }
  397. if target == nil {
  398. fmt.Fprintln(cli.out, "No targets found, please provide a specific tag in order to sign it")
  399. return nil
  400. }
  401. fmt.Fprintln(cli.out, "Signing and pushing trust metadata")
  402. repo, err := cli.getNotaryRepository(repoInfo, authConfig, "push", "pull")
  403. if err != nil {
  404. fmt.Fprintf(cli.out, "Error establishing connection to notary repository: %s\n", err)
  405. return err
  406. }
  407. // get the latest repository metadata so we can figure out which roles to sign
  408. _, err = repo.Update(false)
  409. switch err.(type) {
  410. case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist:
  411. keys := repo.CryptoService.ListKeys(data.CanonicalRootRole)
  412. var rootKeyID string
  413. // always select the first root key
  414. if len(keys) > 0 {
  415. sort.Strings(keys)
  416. rootKeyID = keys[0]
  417. } else {
  418. rootPublicKey, err := repo.CryptoService.Create(data.CanonicalRootRole, "", data.ECDSAKey)
  419. if err != nil {
  420. return err
  421. }
  422. rootKeyID = rootPublicKey.ID()
  423. }
  424. // Initialize the notary repository with a remotely managed snapshot key
  425. if err := repo.Initialize(rootKeyID, data.CanonicalSnapshotRole); err != nil {
  426. return notaryError(repoInfo.FullName(), err)
  427. }
  428. fmt.Fprintf(cli.out, "Finished initializing %q\n", repoInfo.FullName())
  429. err = repo.AddTarget(target, data.CanonicalTargetsRole)
  430. case nil:
  431. // already initialized and we have successfully downloaded the latest metadata
  432. err = cli.addTargetToAllSignableRoles(repo, target)
  433. default:
  434. return notaryError(repoInfo.FullName(), err)
  435. }
  436. if err == nil {
  437. err = repo.Publish()
  438. }
  439. if err != nil {
  440. fmt.Fprintf(cli.out, "Failed to sign %q:%s - %s\n", repoInfo.FullName(), tag, err.Error())
  441. return notaryError(repoInfo.FullName(), err)
  442. }
  443. fmt.Fprintf(cli.out, "Successfully signed %q:%s\n", repoInfo.FullName(), tag)
  444. return nil
  445. }
  446. // Attempt to add the image target to all the top level delegation roles we can
  447. // (based on whether we have the signing key and whether the role's path allows
  448. // us to).
  449. // If there are no delegation roles, we add to the targets role.
  450. func (cli *DockerCli) addTargetToAllSignableRoles(repo *client.NotaryRepository, target *client.Target) error {
  451. var signableRoles []string
  452. // translate the full key names, which includes the GUN, into just the key IDs
  453. allCanonicalKeyIDs := make(map[string]struct{})
  454. for fullKeyID := range repo.CryptoService.ListAllKeys() {
  455. allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{}
  456. }
  457. allDelegationRoles, err := repo.GetDelegationRoles()
  458. if err != nil {
  459. return err
  460. }
  461. // if there are no delegation roles, then just try to sign it into the targets role
  462. if len(allDelegationRoles) == 0 {
  463. return repo.AddTarget(target, data.CanonicalTargetsRole)
  464. }
  465. // there are delegation roles, find every delegation role we have a key for, and
  466. // attempt to sign into into all those roles.
  467. for _, delegationRole := range allDelegationRoles {
  468. // We do not support signing any delegation role that isn't a direct child of the targets role.
  469. // Also don't bother checking the keys if we can't add the target
  470. // to this role due to path restrictions
  471. if path.Dir(delegationRole.Name) != data.CanonicalTargetsRole || !delegationRole.CheckPaths(target.Name) {
  472. continue
  473. }
  474. for _, canonicalKeyID := range delegationRole.KeyIDs {
  475. if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok {
  476. signableRoles = append(signableRoles, delegationRole.Name)
  477. break
  478. }
  479. }
  480. }
  481. if len(signableRoles) == 0 {
  482. return fmt.Errorf("no valid signing keys for delegation roles")
  483. }
  484. return repo.AddTarget(target, signableRoles...)
  485. }