trust.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. )
  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(
  162. cli.trustDirectory(), repoInfo.FullName(), server, tr, cli.getPassphraseRetriever(),
  163. trustpinning.TrustPinConfig{})
  164. }
  165. func convertTarget(t client.Target) (target, error) {
  166. h, ok := t.Hashes["sha256"]
  167. if !ok {
  168. return target{}, errors.New("no valid hash, expecting sha256")
  169. }
  170. return target{
  171. reference: registry.ParseReference(t.Name),
  172. digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)),
  173. size: t.Length,
  174. }, nil
  175. }
  176. func (cli *DockerCli) getPassphraseRetriever() passphrase.Retriever {
  177. aliasMap := map[string]string{
  178. "root": "root",
  179. "snapshot": "repository",
  180. "targets": "repository",
  181. "default": "repository",
  182. }
  183. baseRetriever := passphrase.PromptRetrieverWithInOut(cli.in, cli.out, aliasMap)
  184. env := map[string]string{
  185. "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"),
  186. "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  187. "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  188. "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  189. }
  190. return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) {
  191. if v := env[alias]; v != "" {
  192. return v, numAttempts > 1, nil
  193. }
  194. // For non-root roles, we can also try the "default" alias if it is specified
  195. if v := env["default"]; v != "" && alias != data.CanonicalRootRole {
  196. return v, numAttempts > 1, nil
  197. }
  198. return baseRetriever(keyName, alias, createNew, numAttempts)
  199. }
  200. }
  201. func (cli *DockerCli) trustedReference(ctx context.Context, ref reference.NamedTagged) (reference.Canonical, error) {
  202. repoInfo, err := registry.ParseRepositoryInfo(ref)
  203. if err != nil {
  204. return nil, err
  205. }
  206. // Resolve the Auth config relevant for this server
  207. authConfig := cli.resolveAuthConfig(ctx, repoInfo.Index)
  208. notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig, "pull")
  209. if err != nil {
  210. fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err)
  211. return nil, err
  212. }
  213. t, err := notaryRepo.GetTargetByName(ref.Tag(), releasesRole, data.CanonicalTargetsRole)
  214. if err != nil {
  215. return nil, err
  216. }
  217. // Only list tags in the top level targets role or the releases delegation role - ignore
  218. // all other delegation roles
  219. if t.Role != releasesRole && t.Role != data.CanonicalTargetsRole {
  220. return nil, notaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.Tag()))
  221. }
  222. r, err := convertTarget(t.Target)
  223. if err != nil {
  224. return nil, err
  225. }
  226. return reference.WithDigest(ref, r.digest)
  227. }
  228. func (cli *DockerCli) tagTrusted(ctx context.Context, trustedRef reference.Canonical, ref reference.NamedTagged) error {
  229. fmt.Fprintf(cli.out, "Tagging %s as %s\n", trustedRef.String(), ref.String())
  230. options := types.ImageTagOptions{
  231. Force: true,
  232. }
  233. return cli.client.ImageTag(ctx, trustedRef.String(), ref.String(), options)
  234. }
  235. func notaryError(repoName string, err error) error {
  236. switch err.(type) {
  237. case *json.SyntaxError:
  238. logrus.Debugf("Notary syntax error: %s", err)
  239. 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)
  240. case signed.ErrExpired:
  241. return fmt.Errorf("Error: remote repository %s out-of-date: %v", repoName, err)
  242. case trustmanager.ErrKeyNotFound:
  243. return fmt.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err)
  244. case *net.OpError:
  245. return fmt.Errorf("Error: error contacting notary server: %v", err)
  246. case store.ErrMetaNotFound:
  247. return fmt.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err)
  248. case signed.ErrInvalidKeyType:
  249. return fmt.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err)
  250. case signed.ErrNoKeys:
  251. return fmt.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err)
  252. case signed.ErrLowVersion:
  253. return fmt.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err)
  254. case signed.ErrRoleThreshold:
  255. return fmt.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err)
  256. case client.ErrRepositoryNotExist:
  257. return fmt.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err)
  258. case signed.ErrInsufficientSignatures:
  259. return fmt.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err)
  260. }
  261. return err
  262. }
  263. func (cli *DockerCli) trustedPull(ctx context.Context, repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
  264. var refs []target
  265. notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig, "pull")
  266. if err != nil {
  267. fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err)
  268. return err
  269. }
  270. if ref.String() == "" {
  271. // List all targets
  272. targets, err := notaryRepo.ListTargets(releasesRole, data.CanonicalTargetsRole)
  273. if err != nil {
  274. return notaryError(repoInfo.FullName(), err)
  275. }
  276. for _, tgt := range targets {
  277. t, err := convertTarget(tgt.Target)
  278. if err != nil {
  279. fmt.Fprintf(cli.out, "Skipping target for %q\n", repoInfo.Name())
  280. continue
  281. }
  282. // Only list tags in the top level targets role or the releases delegation role - ignore
  283. // all other delegation roles
  284. if tgt.Role != releasesRole && tgt.Role != data.CanonicalTargetsRole {
  285. continue
  286. }
  287. refs = append(refs, t)
  288. }
  289. if len(refs) == 0 {
  290. return notaryError(repoInfo.FullName(), fmt.Errorf("No trusted tags for %s", repoInfo.FullName()))
  291. }
  292. } else {
  293. t, err := notaryRepo.GetTargetByName(ref.String(), releasesRole, data.CanonicalTargetsRole)
  294. if err != nil {
  295. return notaryError(repoInfo.FullName(), err)
  296. }
  297. // Only get the tag if it's in the top level targets role or the releases delegation role
  298. // ignore it if it's in any other delegation roles
  299. if t.Role != releasesRole && t.Role != data.CanonicalTargetsRole {
  300. return notaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.String()))
  301. }
  302. logrus.Debugf("retrieving target for %s role\n", t.Role)
  303. r, err := convertTarget(t.Target)
  304. if err != nil {
  305. return err
  306. }
  307. refs = append(refs, r)
  308. }
  309. for i, r := range refs {
  310. displayTag := r.reference.String()
  311. if displayTag != "" {
  312. displayTag = ":" + displayTag
  313. }
  314. fmt.Fprintf(cli.out, "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), repoInfo.Name(), displayTag, r.digest)
  315. ref, err := reference.WithDigest(repoInfo, r.digest)
  316. if err != nil {
  317. return err
  318. }
  319. if err := cli.imagePullPrivileged(ctx, authConfig, ref.String(), requestPrivilege, false); err != nil {
  320. return err
  321. }
  322. // If reference is not trusted, tag by trusted reference
  323. if !r.reference.HasDigest() {
  324. tagged, err := reference.WithTag(repoInfo, r.reference.String())
  325. if err != nil {
  326. return err
  327. }
  328. trustedRef, err := reference.WithDigest(repoInfo, r.digest)
  329. if err != nil {
  330. return err
  331. }
  332. if err := cli.tagTrusted(ctx, trustedRef, tagged); err != nil {
  333. return err
  334. }
  335. }
  336. }
  337. return nil
  338. }
  339. func (cli *DockerCli) trustedPush(ctx context.Context, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
  340. responseBody, err := cli.imagePushPrivileged(ctx, authConfig, ref.String(), requestPrivilege)
  341. if err != nil {
  342. return err
  343. }
  344. defer responseBody.Close()
  345. // If it is a trusted push we would like to find the target entry which match the
  346. // tag provided in the function and then do an AddTarget later.
  347. target := &client.Target{}
  348. // Count the times of calling for handleTarget,
  349. // if it is called more that once, that should be considered an error in a trusted push.
  350. cnt := 0
  351. handleTarget := func(aux *json.RawMessage) {
  352. cnt++
  353. if cnt > 1 {
  354. // handleTarget should only be called one. This will be treated as an error.
  355. return
  356. }
  357. var pushResult distribution.PushResult
  358. err := json.Unmarshal(*aux, &pushResult)
  359. if err == nil && pushResult.Tag != "" && pushResult.Digest.Validate() == nil {
  360. h, err := hex.DecodeString(pushResult.Digest.Hex())
  361. if err != nil {
  362. target = nil
  363. return
  364. }
  365. target.Name = registry.ParseReference(pushResult.Tag).String()
  366. target.Hashes = data.Hashes{string(pushResult.Digest.Algorithm()): h}
  367. target.Length = int64(pushResult.Size)
  368. }
  369. }
  370. var tag string
  371. switch x := ref.(type) {
  372. case reference.Canonical:
  373. return errors.New("cannot push a digest reference")
  374. case reference.NamedTagged:
  375. tag = x.Tag()
  376. }
  377. // We want trust signatures to always take an explicit tag,
  378. // otherwise it will act as an untrusted push.
  379. if tag == "" {
  380. if err = jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, nil); err != nil {
  381. return err
  382. }
  383. fmt.Fprintln(cli.out, "No tag specified, skipping trust metadata push")
  384. return nil
  385. }
  386. if err = jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, handleTarget); err != nil {
  387. return err
  388. }
  389. if cnt > 1 {
  390. return fmt.Errorf("internal error: only one call to handleTarget expected")
  391. }
  392. if target == nil {
  393. fmt.Fprintln(cli.out, "No targets found, please provide a specific tag in order to sign it")
  394. return nil
  395. }
  396. fmt.Fprintln(cli.out, "Signing and pushing trust metadata")
  397. repo, err := cli.getNotaryRepository(repoInfo, authConfig, "push", "pull")
  398. if err != nil {
  399. fmt.Fprintf(cli.out, "Error establishing connection to notary repository: %s\n", err)
  400. return err
  401. }
  402. // get the latest repository metadata so we can figure out which roles to sign
  403. err = repo.Update(false)
  404. switch err.(type) {
  405. case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist:
  406. keys := repo.CryptoService.ListKeys(data.CanonicalRootRole)
  407. var rootKeyID string
  408. // always select the first root key
  409. if len(keys) > 0 {
  410. sort.Strings(keys)
  411. rootKeyID = keys[0]
  412. } else {
  413. rootPublicKey, err := repo.CryptoService.Create(data.CanonicalRootRole, "", data.ECDSAKey)
  414. if err != nil {
  415. return err
  416. }
  417. rootKeyID = rootPublicKey.ID()
  418. }
  419. // Initialize the notary repository with a remotely managed snapshot key
  420. if err := repo.Initialize(rootKeyID, data.CanonicalSnapshotRole); err != nil {
  421. return notaryError(repoInfo.FullName(), err)
  422. }
  423. fmt.Fprintf(cli.out, "Finished initializing %q\n", repoInfo.FullName())
  424. err = repo.AddTarget(target, data.CanonicalTargetsRole)
  425. case nil:
  426. // already initialized and we have successfully downloaded the latest metadata
  427. err = cli.addTargetToAllSignableRoles(repo, target)
  428. default:
  429. return notaryError(repoInfo.FullName(), err)
  430. }
  431. if err == nil {
  432. err = repo.Publish()
  433. }
  434. if err != nil {
  435. fmt.Fprintf(cli.out, "Failed to sign %q:%s - %s\n", repoInfo.FullName(), tag, err.Error())
  436. return notaryError(repoInfo.FullName(), err)
  437. }
  438. fmt.Fprintf(cli.out, "Successfully signed %q:%s\n", repoInfo.FullName(), tag)
  439. return nil
  440. }
  441. // Attempt to add the image target to all the top level delegation roles we can
  442. // (based on whether we have the signing key and whether the role's path allows
  443. // us to).
  444. // If there are no delegation roles, we add to the targets role.
  445. func (cli *DockerCli) addTargetToAllSignableRoles(repo *client.NotaryRepository, target *client.Target) error {
  446. var signableRoles []string
  447. // translate the full key names, which includes the GUN, into just the key IDs
  448. allCanonicalKeyIDs := make(map[string]struct{})
  449. for fullKeyID := range repo.CryptoService.ListAllKeys() {
  450. allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{}
  451. }
  452. allDelegationRoles, err := repo.GetDelegationRoles()
  453. if err != nil {
  454. return err
  455. }
  456. // if there are no delegation roles, then just try to sign it into the targets role
  457. if len(allDelegationRoles) == 0 {
  458. return repo.AddTarget(target, data.CanonicalTargetsRole)
  459. }
  460. // there are delegation roles, find every delegation role we have a key for, and
  461. // attempt to sign into into all those roles.
  462. for _, delegationRole := range allDelegationRoles {
  463. // We do not support signing any delegation role that isn't a direct child of the targets role.
  464. // Also don't bother checking the keys if we can't add the target
  465. // to this role due to path restrictions
  466. if path.Dir(delegationRole.Name) != data.CanonicalTargetsRole || !delegationRole.CheckPaths(target.Name) {
  467. continue
  468. }
  469. for _, canonicalKeyID := range delegationRole.KeyIDs {
  470. if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok {
  471. signableRoles = append(signableRoles, delegationRole.Name)
  472. break
  473. }
  474. }
  475. }
  476. if len(signableRoles) == 0 {
  477. return fmt.Errorf("no valid signing keys for delegation roles")
  478. }
  479. return repo.AddTarget(target, signableRoles...)
  480. }