From a0f0c937c42097bea1b767fca886ae24a90fc4da Mon Sep 17 00:00:00 2001 From: silverwind Date: Tue, 17 Nov 2026 05:17:20 +0000 Subject: [PATCH] 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 --- assets/go-licenses.json | 5 -- go.mod | 1 - go.sum | 2 - modules/packages/debian/ar.go | 43 ++++++++++ modules/packages/debian/metadata.go | 18 ++-- modules/packages/debian/metadata_test.go | 82 ++++++++----------- tests/integration/api_packages_debian_test.go | 11 +-- 7 files changed, 86 insertions(+), 76 deletions(-) create mode 100644 modules/packages/debian/ar.go diff --git a/assets/go-licenses.json b/assets/go-licenses.json index 8eeb6e5b485..d88145b8986 100644 --- a/assets/go-licenses.json +++ b/assets/go-licenses.json @@ -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", diff --git a/go.mod b/go.mod index 31305e5f82c..303feea8b5d 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index ba7d1ebe8f5..f58c5f28f9e 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/modules/packages/debian/ar.go b/modules/packages/debian/ar.go new file mode 100644 index 00000000000..5226fa04ca7 --- /dev/null +++ b/modules/packages/debian/ar.go @@ -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 = "!\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 +} diff --git a/modules/packages/debian/metadata.go b/modules/packages/debian/metadata.go index 6a795956585..90590b8d54b 100644 --- a/modules/packages/debian/metadata.go +++ b/modules/packages/debian/metadata.go @@ -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 diff --git a/modules/packages/debian/metadata_test.go b/modules/packages/debian/metadata_test.go index 20d8c5f509c..a894b3120dc 100644 --- a/modules/packages/debian/metadata_test.go +++ b/modules/packages/debian/metadata_test.go @@ -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{ + "!\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) - }) + } }) } }) diff --git a/tests/integration/api_packages_debian_test.go b/tests/integration/api_packages_debian_test.go index e4c7e178759..b86f531f100 100644 --- a/tests/integration/api_packages_debian_test.go +++ b/tests/integration/api_packages_debian_test.go @@ -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, "!\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