fix(packages): replace blakesmith/ar with an in-tree reader (#40401) (#40410)

Backport https://github.com/go-gitea/gitea/pull/40401

https://github.com/blakesmith/ar is unmaintained since 2019 and panics
on a negative member size (https://pkg.go.dev/vuln/GO-2026-6905), with
no fixed version. Debian packages only need a small subset of the `ar`
format, so this reads it in-tree.

- Malformed or truncated archives are rejected with a 400 instead of a
500 or a panic
- Parsing stops after the first `control.tar` member, deb(5) allows only
one

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
silverwind authored and GitHub committed 2026-11-17 05:17:20 +00:00
1 parent 0b5dfdeeea
commit a0f0c937c4
7 files changed
+86 -76

No files matched your search

-5
View File
@@ -139,11 +139,6 @@
"path": "github.com/bits-and-blooms/bitset/LICENSE",
"licenseText": "Copyright (c) 2014 the bitset authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
},
{
"name": "github.com/blakesmith/ar",
"path": "github.com/blakesmith/ar/COPYING",
"licenseText": "Copyright (c) 2013 Blake Smith \u003cblakesmith0@gmail.com\u003e\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n"
},
{
"name": "github.com/blevesearch/bleve/v2",
"path": "github.com/blevesearch/bleve/v2/LICENSE",
-1
View File
@@ -22,7 +22,6 @@ require (
github.com/PuerkitoBio/goquery v1.13.0
github.com/SaveTheRbtz/zstd-seekable-format-go/pkg v0.10.0
github.com/alecthomas/chroma/v2 v2.27.0
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb
github.com/blevesearch/bleve/v2 v2.6.1
github.com/bohde/codel v0.2.0
github.com/buildkite/terminal-to-html/v3 v3.17.1
-2
View File
@@ -85,8 +85,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bits-and-blooms/bitset v1.24.5 h1:654xBVHc23gJMAgOTkPNoCVfiRxuIOAUnAZFtopqJ4w=
github.com/bits-and-blooms/bitset v1.24.5/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4=
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI=
github.com/blevesearch/bleve/v2 v2.6.1 h1:47vLskRTqxvQEtxVPYHjf5KpOgzD2msslXFjvUQCgWQ=
github.com/blevesearch/bleve/v2 v2.6.1/go.mod h1:Dvvx6ZoEBTOj6RSzfk0lEz0wce/qhe2yOUubXeuzd2c=
github.com/blevesearch/bleve_index_api v1.4.1 h1:CYIyecFlI+/RYjzUm+NmDjYbSvk870Bb7f+Vl4b12q8=
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package debian
import (
"io"
"strconv"
"strings"
"gitea.dev/modules/util"
)
const arMagic = "!<arch>\n"
type arReader struct {
io.LimitedReader
pad int64
}
func newArReader(r io.Reader) (*arReader, error) {
var magic [len(arMagic)]byte
if _, err := io.ReadFull(r, magic[:]); err != nil || string(magic[:]) != arMagic {
return nil, GlobalVars().ErrInvalidArchive
}
return &arReader{LimitedReader: io.LimitedReader{R: r}}, nil
}
func (ar *arReader) next() (string, error) {
if _, err := io.CopyN(io.Discard, ar.R, ar.N+ar.pad); err != nil {
return "", GlobalVars().ErrInvalidArchive
}
var header [60]byte
if _, err := io.ReadFull(ar.R, header[:]); err != nil {
return "", util.Iif(err == io.EOF, err, GlobalVars().ErrInvalidArchive)
}
size, err := strconv.ParseInt(strings.TrimRight(string(header[48:58]), " "), 10, 64)
if err != nil || size < 0 || string(header[58:]) != "`\n" {
return "", GlobalVars().ErrInvalidArchive
}
ar.N, ar.pad = size, size%2
return strings.TrimSuffix(strings.TrimRight(string(header[:16]), " "), "/"), nil // GNU ar terminates names with a slash
}
+10 -8
View File
@@ -17,7 +17,6 @@ import (
"gitea.dev/modules/validation"
"gitea.dev/modules/zstd"
"github.com/blakesmith/ar"
"github.com/ulikunitz/xz"
)
@@ -38,6 +37,7 @@ const (
)
var GlobalVars = sync.OnceValue(func() (ret struct {
ErrInvalidArchive error
ErrMissingControlFile error
ErrUnsupportedCompression error
ErrInvalidName error
@@ -49,6 +49,7 @@ var GlobalVars = sync.OnceValue(func() (ret struct {
symbolPattern *regexp.Regexp
},
) {
ret.ErrInvalidArchive = util.NewInvalidArgumentErrorf("package archive is invalid")
ret.ErrMissingControlFile = util.NewInvalidArgumentErrorf("control file is missing")
ret.ErrUnsupportedCompression = util.NewInvalidArgumentErrorf("unsupported compression algorithm")
ret.ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
@@ -90,10 +91,13 @@ func IsValidDistributionOrComponent(s string) bool {
// ParsePackage parses the Debian package file
// https://manpages.debian.org/bullseye/dpkg-dev/deb.5.en.html
func ParsePackage(r io.Reader) (*Package, error) {
arr := ar.NewReader(r)
arr, err := newArReader(r)
if err != nil {
return nil, err
}
for {
hd, err := arr.Next()
name, err := arr.next()
if err == io.EOF {
break
}
@@ -101,11 +105,9 @@ func ParsePackage(r io.Reader) (*Package, error) {
return nil, err
}
if strings.HasPrefix(hd.Name, controlTar) {
if strings.HasPrefix(name, controlTar) {
var inner io.Reader
// https://man7.org/linux/man-pages/man5/deb-split.5.html#FORMAT
// The file names might contain a trailing slash (since dpkg 1.15.6).
switch strings.TrimSuffix(hd.Name[len(controlTar):], "/") {
switch name[len(controlTar):] {
case "":
inner = arr
case ".gz":
@@ -142,7 +144,7 @@ func ParsePackage(r io.Reader) (*Package, error) {
for {
hd, err := tr.Next()
if err == io.EOF {
break
return nil, GlobalVars().ErrMissingControlFile
}
if err != nil {
return nil, err
+32 -50
View File
@@ -7,13 +7,14 @@ import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"strings"
"testing"
"gitea.dev/modules/util"
"gitea.dev/modules/zstd"
"github.com/blakesmith/ar"
"github.com/stretchr/testify/assert"
"github.com/ulikunitz/xz"
)
@@ -28,49 +29,39 @@ const (
)
func TestParsePackage(t *testing.T) {
createArchive := func(files map[string][]byte) io.Reader {
var buf bytes.Buffer
aw := ar.NewWriter(&buf)
aw.WriteGlobalHeader()
for filename, content := range files {
hdr := &ar.Header{
Name: filename,
Mode: 0o600,
Size: int64(len(content)),
}
aw.WriteHeader(hdr)
aw.Write(content)
}
return &buf
member := func(name, content string) string {
return fmt.Sprintf("%-48s%-10d`\n%s%s", name, len(content), content, strings.Repeat("\n", len(content)%2))
}
debianBinary := member("debian-binary", "2.0\n")
t.Run("MissingControlFile", func(t *testing.T) {
data := createArchive(map[string][]byte{"dummy.txt": {}})
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
tw.WriteHeader(&tar.Header{
Name: "control",
Mode: 0o600,
Size: 50,
})
tw.Write([]byte("Package: gitea\nVersion: 1.0.0\nArchitecture: amd64\n"))
tw.Close()
p, err := ParsePackage(data)
assert.Nil(t, p)
assert.ErrorIs(t, err, GlobalVars().ErrMissingControlFile)
t.Run("Invalid", func(t *testing.T) {
for data, expected := range map[string]error{
"!<ARCH>\n" + debianBinary: GlobalVars().ErrInvalidArchive,
arMagic + debianBinary[:20]: GlobalVars().ErrInvalidArchive,
arMagic + debianBinary[:62]: GlobalVars().ErrInvalidArchive,
arMagic + member("control.tar", "")[:58] + "\n\n": GlobalVars().ErrInvalidArchive,
arMagic + fmt.Sprintf("%-48s%-10d`\n", "control.tar", -1): GlobalVars().ErrInvalidArchive,
arMagic + member("dummy.txt", "x"): GlobalVars().ErrMissingControlFile,
arMagic + member("control.tar", "") + member("control.tar", buf.String()): GlobalVars().ErrMissingControlFile,
arMagic + member("control.tar.foo", ""): GlobalVars().ErrUnsupportedCompression,
} {
p, err := ParsePackage(strings.NewReader(data))
assert.Nil(t, p)
assert.ErrorIs(t, err, expected, "%q", data)
}
})
t.Run("Compression", func(t *testing.T) {
t.Run("Unsupported", func(t *testing.T) {
data := createArchive(map[string][]byte{"control.tar.foo": {}})
p, err := ParsePackage(data)
assert.Nil(t, p)
assert.ErrorIs(t, err, GlobalVars().ErrUnsupportedCompression)
})
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
tw.WriteHeader(&tar.Header{
Name: "control",
Mode: 0o600,
Size: 50,
})
tw.Write([]byte("Package: gitea\nVersion: 1.0.0\nArchitecture: amd64\n"))
tw.Close()
cases := []struct {
Extension string
WriterFactory func(io.Writer) io.WriteCloser
@@ -110,21 +101,12 @@ func TestParsePackage(t *testing.T) {
w.Write(buf.Bytes())
w.Close()
data := createArchive(map[string][]byte{"control.tar" + c.Extension: cbuf.Bytes()})
p, err := ParsePackage(data)
assert.NotNil(t, p)
assert.NoError(t, err)
assert.Equal(t, "gitea", p.Name)
t.Run("TrailingSlash", func(t *testing.T) {
data := createArchive(map[string][]byte{"control.tar" + c.Extension + "/": cbuf.Bytes()})
p, err := ParsePackage(data)
for _, suffix := range []string{"", "/"} {
p, err := ParsePackage(strings.NewReader(arMagic + debianBinary + member("control.tar"+c.Extension+suffix, cbuf.String())))
assert.NotNil(t, p)
assert.NoError(t, err)
assert.Equal(t, "gitea", p.Name)
})
}
})
}
})
+1 -10
View File
@@ -22,7 +22,6 @@ import (
packages_cleanup_service "gitea.dev/services/packages/cleanup"
"gitea.dev/tests"
"github.com/blakesmith/ar"
"github.com/stretchr/testify/assert"
)
@@ -49,15 +48,7 @@ func TestPackageDebian(t *testing.T) {
zw.Close()
var buf bytes.Buffer
aw := ar.NewWriter(&buf)
aw.WriteGlobalHeader()
hdr := &ar.Header{
Name: "control.tar.gz",
Mode: 0o600,
Size: int64(cbuf.Len()),
}
aw.WriteHeader(hdr)
aw.Write(cbuf.Bytes())
fmt.Fprintf(&buf, "!<arch>\n%-48s%-10d`\n%s%s", "control.tar.gz", cbuf.Len(), cbuf.Bytes(), strings.Repeat("\n", cbuf.Len()%2))
// if you'd like to do some tests manually, uncomment the WriteFile line, then you will get some "deb" package files:
// OWNER= PASS= DIST= COMP= ; curl -X PUT "http://$OWNER:$PASS@localhost:3000/api/packages/$OWNER/debian/pool/$DIST/$COMP/upload" -T /tmp/gitea_test_debian_gitea_1.0.3_amd64.deb