Skip to content

Parse panics with "index out of range [0]" when an integer element such as (0002,0000) or Rows has length 0 #392

Open

Description

@JayOfTheKeyboard

Summary

dicom.Parse panics on a 140-byte file whose File Meta Information Group Length (0002,0000) is UL with a value length of 0. The empty UL decodes to an empty []int, and readHeader takes [0] from it without checking the length (read.go:230):

metaLen := maybeMetaLen.Value.GetValue().([]int)[0]

Nothing recovers the panic, so any program that parses files it did not create with dicom.Parse crashes instead of getting an error.

Reproduction (main at 8ae5137)

package main

import (
	"bytes"
	"fmt"

	"github.com/suyashkumar/dicom"
)

func main() {
	var b bytes.Buffer
	b.Write(make([]byte, 128)) // preamble
	b.WriteString("DICM")
	// (0002,0000) VR=UL, length 0
	b.Write([]byte{0x02, 0x00, 0x00, 0x00, 'U', 'L', 0x00, 0x00})
	data := b.Bytes()
	_, err := dicom.Parse(bytes.NewReader(data), int64(len(data)), nil)
	fmt.Println("err =", err)
}
panic: runtime error: index out of range [0] with length 0

github.com/suyashkumar/dicom.(*reader).readHeader(...)
github.com/suyashkumar/dicom.NewParser(...)
github.com/suyashkumar/dicom.parseInternal(...)
github.com/suyashkumar/dicom.Parse(...)

Second site

readNativeFrames does the same with MustGetInts(...)[0] for Rows, Columns, BitsAllocated and SamplesPerPixel (read.go:446-454). A file with a valid header and an empty US Rows and Columns before PixelData panics there the same way. read.go:433 (NumberOfFrames) and write.go:322 index the same way, but I haven't produced a panic from either.

Expected

An error, the same as for other malformed headers. ErrorMetaElementGroupLength looks like the right one for read.go:230.

Fix

I have a fix ready. An empty (0002,0000) is treated like a missing one, so it returns ErrorMetaElementGroupLength unless AllowMissingMetaElementGroupLength is set. readNativeFrames reads Rows, Columns, BitsAllocated and SamplesPerPixel through a small helper that returns an error for an empty value. A new TestParse_EmptyIntElements covers both sites and panics without the fix, and make test passes with it. I'll open a PR if that sounds right to you.

(Found by fuzzing and reproduced with the help of an AI coding assistant.)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions