trust.go 18 KB

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