trust.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package image
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "path"
  9. "sort"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/distribution/reference"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/cli/command"
  14. "github.com/docker/docker/cli/trust"
  15. "github.com/docker/docker/pkg/jsonmessage"
  16. "github.com/docker/docker/registry"
  17. "github.com/docker/notary/client"
  18. "github.com/docker/notary/tuf/data"
  19. "github.com/opencontainers/go-digest"
  20. "golang.org/x/net/context"
  21. )
  22. type target struct {
  23. name string
  24. digest digest.Digest
  25. size int64
  26. }
  27. // trustedPush handles content trust pushing of an image
  28. func trustedPush(ctx context.Context, cli *command.DockerCli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
  29. responseBody, err := imagePushPrivileged(ctx, cli, authConfig, ref, requestPrivilege)
  30. if err != nil {
  31. return err
  32. }
  33. defer responseBody.Close()
  34. return PushTrustedReference(cli, repoInfo, ref, authConfig, responseBody)
  35. }
  36. // PushTrustedReference pushes a canonical reference to the trust server.
  37. func PushTrustedReference(cli *command.DockerCli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, in io.Reader) error {
  38. // If it is a trusted push we would like to find the target entry which match the
  39. // tag provided in the function and then do an AddTarget later.
  40. target := &client.Target{}
  41. // Count the times of calling for handleTarget,
  42. // if it is called more that once, that should be considered an error in a trusted push.
  43. cnt := 0
  44. handleTarget := func(aux *json.RawMessage) {
  45. cnt++
  46. if cnt > 1 {
  47. // handleTarget should only be called one. This will be treated as an error.
  48. return
  49. }
  50. var pushResult types.PushResult
  51. err := json.Unmarshal(*aux, &pushResult)
  52. if err == nil && pushResult.Tag != "" {
  53. if dgst, err := digest.Parse(pushResult.Digest); err == nil {
  54. h, err := hex.DecodeString(dgst.Hex())
  55. if err != nil {
  56. target = nil
  57. return
  58. }
  59. target.Name = pushResult.Tag
  60. target.Hashes = data.Hashes{string(dgst.Algorithm()): h}
  61. target.Length = int64(pushResult.Size)
  62. }
  63. }
  64. }
  65. var tag string
  66. switch x := ref.(type) {
  67. case reference.Canonical:
  68. return errors.New("cannot push a digest reference")
  69. case reference.NamedTagged:
  70. tag = x.Tag()
  71. default:
  72. // We want trust signatures to always take an explicit tag,
  73. // otherwise it will act as an untrusted push.
  74. if err := jsonmessage.DisplayJSONMessagesToStream(in, cli.Out(), nil); err != nil {
  75. return err
  76. }
  77. fmt.Fprintln(cli.Out(), "No tag specified, skipping trust metadata push")
  78. return nil
  79. }
  80. if err := jsonmessage.DisplayJSONMessagesToStream(in, cli.Out(), handleTarget); err != nil {
  81. return err
  82. }
  83. if cnt > 1 {
  84. return fmt.Errorf("internal error: only one call to handleTarget expected")
  85. }
  86. if target == nil {
  87. fmt.Fprintln(cli.Out(), "No targets found, please provide a specific tag in order to sign it")
  88. return nil
  89. }
  90. fmt.Fprintln(cli.Out(), "Signing and pushing trust metadata")
  91. repo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "push", "pull")
  92. if err != nil {
  93. fmt.Fprintf(cli.Out(), "Error establishing connection to notary repository: %s\n", err)
  94. return err
  95. }
  96. // get the latest repository metadata so we can figure out which roles to sign
  97. err = repo.Update(false)
  98. switch err.(type) {
  99. case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist:
  100. keys := repo.CryptoService.ListKeys(data.CanonicalRootRole)
  101. var rootKeyID string
  102. // always select the first root key
  103. if len(keys) > 0 {
  104. sort.Strings(keys)
  105. rootKeyID = keys[0]
  106. } else {
  107. rootPublicKey, err := repo.CryptoService.Create(data.CanonicalRootRole, "", data.ECDSAKey)
  108. if err != nil {
  109. return err
  110. }
  111. rootKeyID = rootPublicKey.ID()
  112. }
  113. // Initialize the notary repository with a remotely managed snapshot key
  114. if err := repo.Initialize([]string{rootKeyID}, data.CanonicalSnapshotRole); err != nil {
  115. return trust.NotaryError(repoInfo.Name.Name(), err)
  116. }
  117. fmt.Fprintf(cli.Out(), "Finished initializing %q\n", repoInfo.Name.Name())
  118. err = repo.AddTarget(target, data.CanonicalTargetsRole)
  119. case nil:
  120. // already initialized and we have successfully downloaded the latest metadata
  121. err = addTargetToAllSignableRoles(repo, target)
  122. default:
  123. return trust.NotaryError(repoInfo.Name.Name(), err)
  124. }
  125. if err == nil {
  126. err = repo.Publish()
  127. }
  128. if err != nil {
  129. fmt.Fprintf(cli.Out(), "Failed to sign %q:%s - %s\n", repoInfo.Name.Name(), tag, err.Error())
  130. return trust.NotaryError(repoInfo.Name.Name(), err)
  131. }
  132. fmt.Fprintf(cli.Out(), "Successfully signed %q:%s\n", repoInfo.Name.Name(), tag)
  133. return nil
  134. }
  135. // Attempt to add the image target to all the top level delegation roles we can
  136. // (based on whether we have the signing key and whether the role's path allows
  137. // us to).
  138. // If there are no delegation roles, we add to the targets role.
  139. func addTargetToAllSignableRoles(repo *client.NotaryRepository, target *client.Target) error {
  140. var signableRoles []string
  141. // translate the full key names, which includes the GUN, into just the key IDs
  142. allCanonicalKeyIDs := make(map[string]struct{})
  143. for fullKeyID := range repo.CryptoService.ListAllKeys() {
  144. allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{}
  145. }
  146. allDelegationRoles, err := repo.GetDelegationRoles()
  147. if err != nil {
  148. return err
  149. }
  150. // if there are no delegation roles, then just try to sign it into the targets role
  151. if len(allDelegationRoles) == 0 {
  152. return repo.AddTarget(target, data.CanonicalTargetsRole)
  153. }
  154. // there are delegation roles, find every delegation role we have a key for, and
  155. // attempt to sign into into all those roles.
  156. for _, delegationRole := range allDelegationRoles {
  157. // We do not support signing any delegation role that isn't a direct child of the targets role.
  158. // Also don't bother checking the keys if we can't add the target
  159. // to this role due to path restrictions
  160. if path.Dir(delegationRole.Name) != data.CanonicalTargetsRole || !delegationRole.CheckPaths(target.Name) {
  161. continue
  162. }
  163. for _, canonicalKeyID := range delegationRole.KeyIDs {
  164. if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok {
  165. signableRoles = append(signableRoles, delegationRole.Name)
  166. break
  167. }
  168. }
  169. }
  170. if len(signableRoles) == 0 {
  171. return fmt.Errorf("no valid signing keys for delegation roles")
  172. }
  173. return repo.AddTarget(target, signableRoles...)
  174. }
  175. // imagePushPrivileged push the image
  176. func imagePushPrivileged(ctx context.Context, cli *command.DockerCli, authConfig types.AuthConfig, ref reference.Named, requestPrivilege types.RequestPrivilegeFunc) (io.ReadCloser, error) {
  177. encodedAuth, err := command.EncodeAuthToBase64(authConfig)
  178. if err != nil {
  179. return nil, err
  180. }
  181. options := types.ImagePushOptions{
  182. RegistryAuth: encodedAuth,
  183. PrivilegeFunc: requestPrivilege,
  184. }
  185. return cli.Client().ImagePush(ctx, reference.FamiliarString(ref), options)
  186. }
  187. // trustedPull handles content trust pulling of an image
  188. func trustedPull(ctx context.Context, cli *command.DockerCli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
  189. var refs []target
  190. notaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "pull")
  191. if err != nil {
  192. fmt.Fprintf(cli.Out(), "Error establishing connection to trust repository: %s\n", err)
  193. return err
  194. }
  195. if tagged, isTagged := ref.(reference.NamedTagged); !isTagged {
  196. // List all targets
  197. targets, err := notaryRepo.ListTargets(trust.ReleasesRole, data.CanonicalTargetsRole)
  198. if err != nil {
  199. return trust.NotaryError(ref.Name(), err)
  200. }
  201. for _, tgt := range targets {
  202. t, err := convertTarget(tgt.Target)
  203. if err != nil {
  204. fmt.Fprintf(cli.Out(), "Skipping target for %q\n", reference.FamiliarName(ref))
  205. continue
  206. }
  207. // Only list tags in the top level targets role or the releases delegation role - ignore
  208. // all other delegation roles
  209. if tgt.Role != trust.ReleasesRole && tgt.Role != data.CanonicalTargetsRole {
  210. continue
  211. }
  212. refs = append(refs, t)
  213. }
  214. if len(refs) == 0 {
  215. return trust.NotaryError(ref.Name(), fmt.Errorf("No trusted tags for %s", ref.Name()))
  216. }
  217. } else {
  218. t, err := notaryRepo.GetTargetByName(tagged.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
  219. if err != nil {
  220. return trust.NotaryError(ref.Name(), err)
  221. }
  222. // Only get the tag if it's in the top level targets role or the releases delegation role
  223. // ignore it if it's in any other delegation roles
  224. if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
  225. return trust.NotaryError(ref.Name(), fmt.Errorf("No trust data for %s", tagged.Tag()))
  226. }
  227. logrus.Debugf("retrieving target for %s role\n", t.Role)
  228. r, err := convertTarget(t.Target)
  229. if err != nil {
  230. return err
  231. }
  232. refs = append(refs, r)
  233. }
  234. for i, r := range refs {
  235. displayTag := r.name
  236. if displayTag != "" {
  237. displayTag = ":" + displayTag
  238. }
  239. fmt.Fprintf(cli.Out(), "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), reference.FamiliarName(ref), displayTag, r.digest)
  240. trustedRef, err := reference.WithDigest(reference.TrimNamed(ref), r.digest)
  241. if err != nil {
  242. return err
  243. }
  244. if err := imagePullPrivileged(ctx, cli, authConfig, reference.FamiliarString(trustedRef), requestPrivilege, false); err != nil {
  245. return err
  246. }
  247. tagged, err := reference.WithTag(reference.TrimNamed(ref), r.name)
  248. if err != nil {
  249. return err
  250. }
  251. if err := TagTrusted(ctx, cli, trustedRef, tagged); err != nil {
  252. return err
  253. }
  254. }
  255. return nil
  256. }
  257. // imagePullPrivileged pulls the image and displays it to the output
  258. func imagePullPrivileged(ctx context.Context, cli *command.DockerCli, authConfig types.AuthConfig, ref string, requestPrivilege types.RequestPrivilegeFunc, all bool) error {
  259. encodedAuth, err := command.EncodeAuthToBase64(authConfig)
  260. if err != nil {
  261. return err
  262. }
  263. options := types.ImagePullOptions{
  264. RegistryAuth: encodedAuth,
  265. PrivilegeFunc: requestPrivilege,
  266. All: all,
  267. }
  268. responseBody, err := cli.Client().ImagePull(ctx, ref, options)
  269. if err != nil {
  270. return err
  271. }
  272. defer responseBody.Close()
  273. return jsonmessage.DisplayJSONMessagesToStream(responseBody, cli.Out(), nil)
  274. }
  275. // TrustedReference returns the canonical trusted reference for an image reference
  276. func TrustedReference(ctx context.Context, cli *command.DockerCli, ref reference.NamedTagged, rs registry.Service) (reference.Canonical, error) {
  277. var (
  278. repoInfo *registry.RepositoryInfo
  279. err error
  280. )
  281. if rs != nil {
  282. repoInfo, err = rs.ResolveRepository(ref)
  283. } else {
  284. repoInfo, err = registry.ParseRepositoryInfo(ref)
  285. }
  286. if err != nil {
  287. return nil, err
  288. }
  289. // Resolve the Auth config relevant for this server
  290. authConfig := command.ResolveAuthConfig(ctx, cli, repoInfo.Index)
  291. notaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "pull")
  292. if err != nil {
  293. fmt.Fprintf(cli.Out(), "Error establishing connection to trust repository: %s\n", err)
  294. return nil, err
  295. }
  296. t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
  297. if err != nil {
  298. return nil, trust.NotaryError(repoInfo.Name.Name(), err)
  299. }
  300. // Only list tags in the top level targets role or the releases delegation role - ignore
  301. // all other delegation roles
  302. if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
  303. return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("No trust data for %s", ref.Tag()))
  304. }
  305. r, err := convertTarget(t.Target)
  306. if err != nil {
  307. return nil, err
  308. }
  309. return reference.WithDigest(reference.TrimNamed(ref), r.digest)
  310. }
  311. func convertTarget(t client.Target) (target, error) {
  312. h, ok := t.Hashes["sha256"]
  313. if !ok {
  314. return target{}, errors.New("no valid hash, expecting sha256")
  315. }
  316. return target{
  317. name: t.Name,
  318. digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)),
  319. size: t.Length,
  320. }, nil
  321. }
  322. // TagTrusted tags a trusted ref
  323. func TagTrusted(ctx context.Context, cli *command.DockerCli, trustedRef reference.Canonical, ref reference.NamedTagged) error {
  324. // Use familiar references when interacting with client and output
  325. familiarRef := reference.FamiliarString(ref)
  326. trustedFamiliarRef := reference.FamiliarString(trustedRef)
  327. fmt.Fprintf(cli.Out(), "Tagging %s as %s\n", trustedFamiliarRef, familiarRef)
  328. return cli.Client().ImageTag(ctx, trustedFamiliarRef, familiarRef)
  329. }