golang/go

html/template: runtime error: slice bounds out of range

dvyukov opened this issue · 3 comments

The following program crashes with panic:

package main

import (
    "html/template"
    "io/ioutil"
)

func main() {
    t, err := template.New("foo").Parse(string(data))
    if err != nil {
        return
    }
    t.Execute(ioutil.Discard, nil)
}

var data = "<style>.000000000000" +
    "00.0000000000V000000" +
    "000\x880000000000000000" +
    "00\xa4000\x8e\x9200\x8b\xe0\x85\xbd000000" +
    "0</style"
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
html/template.contextAfterText(0x20000000001, 0x0, 0xc208020126, 0x52, 0x5a, 0x0, 0x0, 0x6)
    src/html/template/escape.go:671 +0x2db
html/template.(*escaper).escapeText(0xc208010540, 0x20000000001, 0x0, 0xc208014810, 0x0, 0x0)
    src/html/template/escape.go:596 +0x199
html/template.(*escaper).escape(0xc208010540, 0x0, 0x0, 0x7f4c7b7951e8, 0xc208014810, 0x700000000000000, 0x0)
    src/html/template/escape.go:129 +0x31a
html/template.(*escaper).escapeList(0xc208010540, 0x0, 0x0, 0xc2080147e0, 0x0, 0x0)
    src/html/template/escape.go:440 +0x1c9
html/template.(*escaper).escapeListConditionally(0xc208010500, 0x0, 0x0, 0xc2080147e0, 0xc2080419b0, 0x0, 0x0, 0x7f4c7b941000)
    src/html/template/escape.go:455 +0x4be
html/template.(*escaper).escapeTemplateBody(0xc208010500, 0x0, 0x0, 0xc208010440, 0x0, 0x0, 0xae00000000000058)
    src/html/template/escape.go:573 +0x1e2
html/template.(*escaper).computeOutCtx(0xc208010500, 0x0, 0x0, 0xc208010440, 0x0, 0x0)
    src/html/template/escape.go:534 +0xc9
html/template.(*escaper).escapeTree(0xc208010500, 0x0, 0x0, 0x7f4c7b795230, 0xc2080147e0, 0x5ba240, 0x3, 0x0, 0x0, 0x0, ...)
    src/html/template/escape.go:527 +0x77f
html/template.escapeTemplate(0xc2080146f0, 0x7f4c7b795230, 0xc2080147e0, 0x5ba240, 0x3, 0x0, 0x0)
    src/html/template/escape.go:23 +0x334
html/template.(*Template).escape(0xc2080146f0, 0x0, 0x0)
    src/html/template/template.go:85 +0x35d
html/template.(*Template).Execute(0xc2080146f0, 0x7f4c7b7951c0, 0xc20800a4c0, 0x0, 0x0, 0x0, 0x0)
    src/html/template/template.go:101 +0x37
main.main()
    /tmp/htmltempl.go:13 +0x290

on commit ccc76db

The problem occurred because function tSpecialTagEnd made the assumption that a conversion to lowercase kept the size of the string unchanged, which is wrong. The original string was sliced based on an index calculated from the lowercase string, resulting in the error.

Now, with CL https://go-review.googlesource.com/#/c/9502/ this code has been removed. By mere luck, it also fixed this problem. We killed multiple birds with the same stone.

I have checked that the other calls to ToLower in the same package are safe.
This issue can be closed.

Test before closing please.

Fixed at tip (tested).