trust.go 18 KB

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