github.com/olljanat/moby@v1.13.1/cli/command/image/trust.go (about)

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