Skip to content

Commit

Permalink
Validate digest length on parsing
Browse files Browse the repository at this point in the history
Signed-off-by: Tonis Tiigi <[email protected]>
  • Loading branch information
tonistiigi committed Dec 3, 2015
1 parent 511bed8 commit 9721254
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
8 changes: 7 additions & 1 deletion digest.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ var (
// ErrDigestInvalidFormat returned when digest format invalid.
ErrDigestInvalidFormat = fmt.Errorf("invalid checksum digest format")

// ErrDigestInvalidLength returned when digest has invalid length.
ErrDigestInvalidLength = fmt.Errorf("invalid checksum digest length")

// ErrDigestUnsupported returned when the digest algorithm is unsupported.
ErrDigestUnsupported = fmt.Errorf("unsupported digest algorithm")
)
Expand Down Expand Up @@ -126,8 +129,11 @@ func (d Digest) Validate() error {
return ErrDigestInvalidFormat
}

switch Algorithm(s[:i]) {
switch algorithm := Algorithm(s[:i]); algorithm {
case SHA256, SHA384, SHA512:
if algorithm.Size()*2 != len(s[i+1:]) {
return ErrDigestInvalidLength
}
break
default:
return ErrDigestUnsupported
Expand Down
10 changes: 10 additions & 0 deletions digest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ func TestParseDigest(t *testing.T) {
input: "sha256:d41d8cd98f00b204e9800m98ecf8427e",
err: ErrDigestInvalidFormat,
},
{
// too short
input: "sha256:abcdef0123456789",
err: ErrDigestInvalidLength,
},
{
// too short (from different algorithm)
input: "sha512:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
err: ErrDigestInvalidLength,
},
{
input: "foo:d41d8cd98f00b204e9800998ecf8427e",
err: ErrDigestUnsupported,
Expand Down
9 changes: 9 additions & 0 deletions digester.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ func (a Algorithm) String() string {
return string(a)
}

// Size returns number of bytes returned by the hash.
func (a Algorithm) Size() int {
h, ok := algorithms[a]
if !ok {
return 0
}
return h.Size()
}

// Set implemented to allow use of Algorithm as a command line flag.
func (a *Algorithm) Set(value string) error {
if value == "" {
Expand Down

0 comments on commit 9721254

Please sign in to comment.