Debian Codegraph @

content/reader.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package content
17
18 import (
19 "bytes"
20 "errors"
21 "fmt"
22 "io"
23
24 "github.com/opencontainers/go-digest"
25 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
26 )
27
28 // maxInitialBufferSize bounds the buffer that ReadAll pre-allocates from
29 // desc.Size before any content is read. desc.Size is attacker-controllable: a
30 // crafted OCI layout index.json can declare an arbitrarily large Size (e.g.
31 // 2^62), and make([]byte, desc.Size) on such a value triggers a runtime panic
32 // ("makeslice: len out of range") before any allocation occurs. ReadAll caps
33 // the initial allocation at this value and grows the buffer as it reads, so the
34 // declared size is never trusted for allocation while legitimately large
35 // content (e.g. plugin or chart layers) is still read in full.
36 const maxInitialBufferSize = 32 * 1024 * 1024 // 32 MiB
37
38 var (
39 // ErrInvalidDescriptorSize is returned by ReadAll() when
40 // the descriptor has an invalid size.
41 ErrInvalidDescriptorSize = errors.New("invalid descriptor size")
42
43 // ErrMismatchedDigest is returned by ReadAll() when
44 // the descriptor has an invalid digest.
45 ErrMismatchedDigest = errors.New("mismatched digest")
46
47 // ErrTrailingData is returned by ReadAll() when
48 // there exists trailing data unread when the read terminates.
49 ErrTrailingData = errors.New("trailing data")
50 )
51
52 var (
53 // errEarlyVerify is returned by VerifyReader.Verify() when
54 // Verify() is called before completing reading the entire content blob.
55 errEarlyVerify = errors.New("early verify")
56 )
57
58 // VerifyReader reads the content described by its descriptor and verifies
59 // against its size and digest.
60 type VerifyReader struct {
61 base *io.LimitedReader
62 verifier digest.Verifier
63 verified bool
64 err error
65 }
66
67 // Read reads up to len(p) bytes into p. It returns the number of bytes
68 // read (0 <= n <= len(p)) and any error encountered.
69 func (vr *VerifyReader) Read(p []byte) (n int, err error) {
70 if vr.err != nil {
71 return 0, vr.err
72 }
73
74 n, err = vr.base.Read(p)
75 if err != nil {
76 if err == io.EOF && vr.base.N > 0 {
77 err = io.ErrUnexpectedEOF
78 }
79 vr.err = err
80 }
81 return
82 }
83
84 // Verify checks for remaining unread content and verifies the read content against the digest
85 func (vr *VerifyReader) Verify() error {
86 if vr.verified {
87 return nil
88 }
89 if vr.err == nil {
90 if vr.base.N > 0 {
91 return errEarlyVerify
92 }
93 } else if vr.err != io.EOF {
94 return vr.err
95 }
96
97 if err := ensureEOF(vr.base.R); err != nil {
98 vr.err = err
99 return vr.err
100 }
101 if !vr.verifier.Verified() {
102 vr.err = ErrMismatchedDigest
103 return vr.err
104 }
105
106 vr.verified = true
107 vr.err = io.EOF
108 return nil
109 }
110
111 // NewVerifyReader wraps r for reading content with verification against desc.
112 func NewVerifyReader(r io.Reader, desc ocispec.Descriptor) *VerifyReader {
113 if err := desc.Digest.Validate(); err != nil {
114 return &VerifyReader{
115 err: fmt.Errorf("failed to validate %s: %w", desc.Digest, err),
116 }
117 }
118 verifier := desc.Digest.Verifier()
119 lr := &io.LimitedReader{
120 R: io.TeeReader(r, verifier),
121 N: desc.Size,
122 }
123 return &VerifyReader{
124 base: lr,
125 verifier: verifier,
126 }
127 }
128
129 // ReadAll safely reads the content described by the descriptor.
130 // The read content is verified against the size and the digest
131 // using a VerifyReader.
132 func ReadAll(r io.Reader, desc ocispec.Descriptor) ([]byte, error) {
133 if desc.Size < 0 {
134 return nil, ErrInvalidDescriptorSize
135 }
136
137 vr := NewVerifyReader(r, desc)
138
139 // Do not pre-allocate desc.Size directly: it is attacker-controllable and a
140 // forged value (e.g. 2^62) would panic make(). Cap the initial allocation
141 // and let the buffer grow as content is read. The VerifyReader enforces the
142 // declared size and digest, so a size that does not match the actual content
143 // still fails verification rather than over-allocating.
144 initialCap := desc.Size
145 if initialCap > maxInitialBufferSize {
146 initialCap = maxInitialBufferSize
147 }
148 buf := bytes.NewBuffer(make([]byte, 0, initialCap))
149 if _, err := buf.ReadFrom(vr); err != nil {
150 if errors.Is(err, io.ErrUnexpectedEOF) {
151 return nil, fmt.Errorf("read failed: expected content size of %d, got %d, for digest %s: %w", desc.Size, buf.Len(), desc.Digest.String(), err)
152 }
153 return nil, fmt.Errorf("read failed: %w", err)
154 }
155 if err := vr.Verify(); err != nil {
156 return nil, err
157 }
158 return buf.Bytes(), nil
159 }
160
161 // ensureEOF ensures the read operation ends with an EOF and no
162 // trailing data is present.
163 func ensureEOF(r io.Reader) error {
164 var peek [1]byte
165 _, err := io.ReadFull(r, peek[:])
166 if err != io.EOF {
167 return ErrTrailingData
168 }
169 return nil
170 }