trust.go 19 KB

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