Skip to content

Commit 162dc71

Browse files
committed
refactor: improve image validation logic and enhance signature checks
1 parent cf5a0aa commit 162dc71

1 file changed

Lines changed: 16 additions & 9 deletions

File tree

‎image/image.go‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,6 @@ var (
2020
)
2121

2222
func IsImage(value []byte) error {
23-
if !hasSupportedImageSignature(value) {
24-
return ErrImageNotValid
25-
}
26-
2723
if hasICOSignature(value) {
2824
if !isICOValid(value) {
2925
return ErrImageNotValid
@@ -32,6 +28,10 @@ func IsImage(value []byte) error {
3228
return nil
3329
}
3430

31+
if !hasSupportedImageSignature(value) {
32+
return ErrImageNotValid
33+
}
34+
3535
if _, _, err := stdimage.DecodeConfig(bytes.NewReader(value)); err != nil {
3636
return ErrImageNotValid
3737
}
@@ -103,9 +103,9 @@ func isICOEntryValid(value []byte, entry []byte, directorySize int) bool {
103103
return false
104104
}
105105

106-
size := binary.LittleEndian.Uint32(entry[8:12])
107-
offset := binary.LittleEndian.Uint32(entry[12:16])
108-
if size == 0 || offset < uint32(directorySize) || offset > uint32(len(value)) || size > uint32(len(value))-offset {
106+
size := littleEndianUint32AsInt(entry[8:12])
107+
offset := littleEndianUint32AsInt(entry[12:16])
108+
if size <= 0 || offset < directorySize || offset > len(value) || size > len(value)-offset {
109109
return false
110110
}
111111

@@ -126,8 +126,8 @@ func isDIBHeaderValid(value []byte) bool {
126126
return false
127127
}
128128

129-
headerSize := binary.LittleEndian.Uint32(value[0:4])
130-
if headerSize < 40 || headerSize > uint32(len(value)) {
129+
headerSize := littleEndianUint32AsInt(value[0:4])
130+
if headerSize < 40 || headerSize > len(value) {
131131
return false
132132
}
133133

@@ -152,3 +152,10 @@ func isDIBBitCountValid(value uint16) bool {
152152
return false
153153
}
154154
}
155+
156+
func littleEndianUint32AsInt(value []byte) int {
157+
return int(value[0]) |
158+
int(value[1])<<8 |
159+
int(value[2])<<16 |
160+
int(value[3])<<24
161+
}

0 commit comments

Comments
 (0)