github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/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  	"github.com/Sirupsen/logrus"
    13  	"github.com/docker/distribution/reference"
    14  	"github.com/docker/docker/api/types"
    15  	"github.com/docker/docker/cli/command"
    16  	"github.com/docker/docker/cli/trust"
    17  	"github.com/docker/docker/pkg/jsonmessage"
    18  	"github.com/docker/docker/registry"
    19  	"github.com/docker/notary/client"
    20  	"github.com/docker/notary/tuf/data"
    21  	"github.com/opencontainers/go-digest"
    22  	"golang.org/x/net/context"
    23  )
    24  
    25  type target struct {
    26  	name   string
    27  	digest digest.Digest
    28  	size   int64
    29  }
    30  
    31  // trustedPush handles content trust pushing of an image
    32  func trustedPush(ctx context.Context, cli *command.DockerCli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
    33  	responseBody, err := imagePushPrivileged(ctx, cli, authConfig, ref, requestPrivilege)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	defer responseBody.Close()
    39  
    40  	return PushTrustedReference(cli, repoInfo, ref, authConfig, responseBody)
    41  }
    42  
    43  // PushTrustedReference pushes a canonical reference to the trust server.
    44  func PushTrustedReference(cli *command.DockerCli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, in io.Reader) error {
    45  	// If it is a trusted push we would like to find the target entry which match the
    46  	// tag provided in the function and then do an AddTarget later.
    47  	target := &client.Target{}
    48  	// Count the times of calling for handleTarget,
    49  	// if it is called more that once, that should be considered an error in a trusted push.
    50  	cnt := 0
    51  	handleTarget := func(aux *json.RawMessage) {
    52  		cnt++
    53  		if cnt > 1 {
    54  			// handleTarget should only be called one. This will be treated as an error.
    55  			return
    56  		}
    57  
    58  		var pushResult types.PushResult
    59  		err := json.Unmarshal(*aux, &pushResult)
    60  		if err == nil && pushResult.Tag != "" {
    61  			if dgst, err := digest.Parse(pushResult.Digest); err == nil {
    62  				h, err := hex.DecodeString(dgst.Hex())
    63  				if err != nil {
    64  					target = nil
    65  					return
    66  				}
    67  				target.Name = pushResult.Tag
    68  				target.Hashes = data.Hashes{string(dgst.Algorithm()): h}
    69  				target.Length = int64(pushResult.Size)
    70  			}
    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.Name.Name(), err)
   133  		}
   134  		fmt.Fprintf(cli.Out(), "Finished initializing %q\n", repoInfo.Name.Name())
   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.Name.Name(), 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.Name.Name(), tag, err.Error())
   149  		return trust.NotaryError(repoInfo.Name.Name(), err)
   150  	}
   151  
   152  	fmt.Fprintf(cli.Out(), "Successfully signed %q:%s\n", repoInfo.Name.Name(), 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 reference.Named, 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, reference.FamiliarString(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(ref.Name(), 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", reference.FamiliarName(ref))
   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(ref.Name(), fmt.Errorf("No trusted tags for %s", ref.Name()))
   249  		}
   250  	} else {
   251  		t, err := notaryRepo.GetTargetByName(tagged.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
   252  		if err != nil {
   253  			return trust.NotaryError(ref.Name(), 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(ref.Name(), 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), reference.FamiliarName(ref), displayTag, r.digest)
   276  
   277  		trustedRef, err := reference.WithDigest(reference.TrimNamed(ref), r.digest)
   278  		if err != nil {
   279  			return err
   280  		}
   281  		if err := imagePullPrivileged(ctx, cli, authConfig, reference.FamiliarString(trustedRef), requestPrivilege, false); err != nil {
   282  			return err
   283  		}
   284  
   285  		tagged, err := reference.WithTag(reference.TrimNamed(ref), r.name)
   286  		if err != nil {
   287  			return err
   288  		}
   289  
   290  		if err := TagTrusted(ctx, cli, trustedRef, tagged); err != nil {
   291  			return err
   292  		}
   293  	}
   294  	return nil
   295  }
   296  
   297  // imagePullPrivileged pulls the image and displays it to the output
   298  func imagePullPrivileged(ctx context.Context, cli *command.DockerCli, authConfig types.AuthConfig, ref string, requestPrivilege types.RequestPrivilegeFunc, all bool) error {
   299  
   300  	encodedAuth, err := command.EncodeAuthToBase64(authConfig)
   301  	if err != nil {
   302  		return err
   303  	}
   304  	options := types.ImagePullOptions{
   305  		RegistryAuth:  encodedAuth,
   306  		PrivilegeFunc: requestPrivilege,
   307  		All:           all,
   308  	}
   309  
   310  	responseBody, err := cli.Client().ImagePull(ctx, ref, options)
   311  	if err != nil {
   312  		return err
   313  	}
   314  	defer responseBody.Close()
   315  
   316  	return jsonmessage.DisplayJSONMessagesToStream(responseBody, cli.Out(), nil)
   317  }
   318  
   319  // TrustedReference returns the canonical trusted reference for an image reference
   320  func TrustedReference(ctx context.Context, cli *command.DockerCli, ref reference.NamedTagged, rs registry.Service) (reference.Canonical, error) {
   321  	var (
   322  		repoInfo *registry.RepositoryInfo
   323  		err      error
   324  	)
   325  	if rs != nil {
   326  		repoInfo, err = rs.ResolveRepository(ref)
   327  	} else {
   328  		repoInfo, err = registry.ParseRepositoryInfo(ref)
   329  	}
   330  	if err != nil {
   331  		return nil, err
   332  	}
   333  
   334  	// Resolve the Auth config relevant for this server
   335  	authConfig := command.ResolveAuthConfig(ctx, cli, repoInfo.Index)
   336  
   337  	notaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "pull")
   338  	if err != nil {
   339  		fmt.Fprintf(cli.Out(), "Error establishing connection to trust repository: %s\n", err)
   340  		return nil, err
   341  	}
   342  
   343  	t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
   344  	if err != nil {
   345  		return nil, trust.NotaryError(repoInfo.Name.Name(), err)
   346  	}
   347  	// Only list tags in the top level targets role or the releases delegation role - ignore
   348  	// all other delegation roles
   349  	if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
   350  		return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("No trust data for %s", ref.Tag()))
   351  	}
   352  	r, err := convertTarget(t.Target)
   353  	if err != nil {
   354  		return nil, err
   355  
   356  	}
   357  
   358  	return reference.WithDigest(reference.TrimNamed(ref), r.digest)
   359  }
   360  
   361  func convertTarget(t client.Target) (target, error) {
   362  	h, ok := t.Hashes["sha256"]
   363  	if !ok {
   364  		return target{}, errors.New("no valid hash, expecting sha256")
   365  	}
   366  	return target{
   367  		name:   t.Name,
   368  		digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)),
   369  		size:   t.Length,
   370  	}, nil
   371  }
   372  
   373  // TagTrusted tags a trusted ref
   374  func TagTrusted(ctx context.Context, cli *command.DockerCli, trustedRef reference.Canonical, ref reference.NamedTagged) error {
   375  	// Use familiar references when interacting with client and output
   376  	familiarRef := reference.FamiliarString(ref)
   377  	trustedFamiliarRef := reference.FamiliarString(trustedRef)
   378  
   379  	fmt.Fprintf(cli.Out(), "Tagging %s as %s\n", trustedFamiliarRef, familiarRef)
   380  
   381  	return cli.Client().ImageTag(ctx, trustedFamiliarRef, familiarRef)
   382  }