From c6870e57fa9f7667c59dd21abd6e8034509b6ada Mon Sep 17 00:00:00 2001
From: xiadanni <xiadanni1@huawei.com>
Date: Thu, 18 Mar 2021 14:41:15 +0800
Subject: [PATCH] docker: prevent an invalid image from crashing docker daemon
 (CVE-2021-21285)

Change-Id: I0cf6a1b268e500a2a004c9d9d33f01a3d4ad5b47
Signed-off-by: xiadanni <xiadanni1@huawei.com>
---
 .../engine/builder/builder-next/adapters/containerimage/pull.go     | 3 +++
 components/engine/distribution/pull_v2.go                           | 6 ++++++
 2 files changed, 9 insertions(+)

diff --git a/components/engine/builder/builder-next/adapters/containerimage/pull.go b/components/engine/builder/builder-next/adapters/containerimage/pull.go
index f6e55f4..4b6eb04 100644
--- a/components/engine/builder/builder-next/adapters/containerimage/pull.go
+++ b/components/engine/builder/builder-next/adapters/containerimage/pull.go
@@ -493,6 +493,9 @@ func (p *puller) Snapshot(ctx context.Context) (cache.ImmutableRef, error) {
 	layers := make([]xfer.DownloadDescriptor, 0, len(mfst.Layers))
 
 	for i, desc := range mfst.Layers {
+		if err := desc.Digest.Validate(); err != nil {
+			return nil, errors.Wrap(err, "layer digest could not be validated")
+		}
 		ongoing.add(desc)
 		layers = append(layers, &layerDescriptor{
 			desc:    desc,
diff --git a/components/engine/distribution/pull_v2.go b/components/engine/distribution/pull_v2.go
index 4150241..98714fd 100644
--- a/components/engine/distribution/pull_v2.go
+++ b/components/engine/distribution/pull_v2.go
@@ -480,6 +480,9 @@ func (p *v2Puller) pullSchema1(ctx context.Context, ref reference.Reference, unv
 	// to top-most, so that the downloads slice gets ordered correctly.
 	for i := len(verifiedManifest.FSLayers) - 1; i >= 0; i-- {
 		blobSum := verifiedManifest.FSLayers[i].BlobSum
+		if err = blobSum.Validate(); err != nil {
+			return "", "", errors.Wrapf(err, "could not validate layer digest %q", blobSum)
+		}
 
 		var throwAway struct {
 			ThrowAway bool `json:"throwaway,omitempty"`
@@ -596,6 +599,9 @@ func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s
 	// Note that the order of this loop is in the direction of bottom-most
 	// to top-most, so that the downloads slice gets ordered correctly.
 	for _, d := range mfst.Layers {
+		if err := d.Digest.Validate(); err != nil {
+			return "", "", errors.Wrapf(err, "could not validate layer digest %q", d.Digest)
+		}
 		layerDescriptor := &v2LayerDescriptor{
 			digest:            d.Digest,
 			repo:              p.repo,
-- 
1.8.3.1

