mirror of
https://github.com/anchore/syft.git
synced 2026-11-04 00:16:38 +01:00
* fix(golang): bound UPX decompression by what the input can justify A UPX block's `sz_unc` was passed straight to `make([]byte, n)`, so four bytes of attacker input spanned the full uint32 range. A ~300KB file could drive multi-GB resident memory, which Go reports as a fatal runtime OOM that no `recover` on this path can contain. Syft parses binaries out of arbitrary images, so that is reachable from any scan. Two bounds do the work, and UPX's own invariants make them exact: - all blocks together reconstruct `p_filesize`, so a running remainder caps the sum. Bounding only per-block would leave the total at (block count x original size), so the remainder is the part that actually closes it - `p_filesize` sizes the output buffer, so it is capped both absolutely and against the size of the file on disk. The absolute cap alone left a ~60 byte header able to claim 500MB; the ratio alone cannot work either, since LZMA encodes a run of N equal bytes in O(log N) and a `go:embed` of 120MB of zeros legitimately packs 209x The output buffer is also allocated on the first block that survives validation rather than up front, so a header claiming a large size with nothing decodable behind it costs nothing. Alongside that, several ways the block loop could be steered off its own buffer: - `parseELFPTLoadOffsets` bounds-checked program headers with `phStart+phentsize > len(buf)`, which overflows for a `p_offset` near 2^64 and lets an out-of-range entry through into a slice index. Switched to the subtraction form, and a `phentsize` shorter than an ELF64 program header is rejected since the reads use fixed offsets - block placement had the same overflow shape, and on failure it skipped the copy and fell through. `outputOffset` derives from the rejected offset, so a `p_offset` at the uint64 ceiling wrapped it to 0 and the next block landed on the reconstructed ELF header, still returning success. Out-of-range placement now ends the block chain, keeping the blocks already placed since those often carry `.go.buildinfo` - the UPX 2-byte LZMA header carries `lc`/`lp` as nibbles and `pb` as three bits, so they can hold values LZMA does not permit. Folded into the props byte they wrap (`lc=15, lp=15, pb=7` gives 465, which truncates to 209) and the stream mis-decodes instead of failing - blocks decode directly into a slice of the output buffer instead of a per-block buffer that is then copied, so one block no longer doubles peak memory - the block count is capped: the size budget alone still allows millions of 12-byte blocks, each spinning up an LZMA reader Verified against the `image-small-upx` fixture, a real `upx --best --lzma` binary: four blocks, max `sz_unc` equal to `p_blocksize` exactly, blocks summing to 0.68 of `p_filesize`, and a 1.96x expansion against the packed file, so every bound holds with headroom on genuine output. Note `p_blocksize` is deliberately not used as a ceiling on `sz_unc`. It adds nothing the remainder does not already cover, and real output sits at exactly `p_blocksize`, so it would run with zero headroom against a value the format does not promise. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * fix(golang): report UPX binaries we cannot unpack as unknowns A packed Go binary we fail to unpack means its packages are silently missing from the SBOM. `getBuildInfo` checked the decompression error for nil and discarded it, so a rejected file surfaced only the original `buildinfo.Read` error, and that one is deliberately silenced because it is usually just "not a Go binary". `decompressUPX` now marks the cases worth reporting with `errUPXDecompress`: it got past the header and the method dispatch and still could not unpack the file. Everything else stays quiet, which matters more than it sounds. `upx` defaults to NRV2B unless `--lzma` is passed and only LZMA is implemented here, so treating any decompression failure as reportable would attach a golang-cataloger unknown to every packed non-Go binary in an image. Making the reportable case opt in rather than the quiet case a growing list also means a guard added later is silent by default. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * refactor(golang): drop the vendored xcoff parser The only thing the golang cataloger read from it was `TargetMachine`, which is the same two magic bytes `getGOARCHFromBin` had already matched on to dispatch there. So a full XCOFF walk (string table, symbol table, every relocation table) ran to recover a value that was already in hand. `getGOARCHFromBin` reads those two bytes directly now. That is also strictly more correct: `xcoff.NewFile` bailed with "no symbol table" when `symptr == 0`, so a stripped XCOFF binary reported no arch at all. Fixtures move to `testdata/xcoff/`, since they are no longer a package's own testdata. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * feat(internal/file): report a reader's real size behind one helper Bounds get written as "does this claim exceed what the reader actually holds", and the subtlety is that a reader's own answer cannot be trusted: an `io.SectionReader` reports the nominal length it was built with, so one constructed with `1<<63-1` will happily claim to hold 8EB. Confirming the last byte is readable is what separates a real size from a nominal one. Returns `(int64, bool)` rather than a bare size, since there are five ways to not know and collapsing them to 0 makes every caller reinvent "0 means stop bounding". The doc also names the wrapper trap: a type embedding `io.ReaderAt` as an interface promotes only `ReadAt`, so it answers no size at all however large the reader beneath it is, and a bound written against it silently does nothing. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * fix(golang): bound every section a reader can expand, not just the name table `CheckSectionNameTable` bounds the one section `elf.NewFile` expands while parsing, which is enough for a caller that only parses. It is not enough for one that goes on to read sections: those are expanded lazily, so a 260KB ELF declaring a compressed `.symtab` drove 1.3GB of allocation through `goversion`, which opens the file with `debug/elf` inside its own package and cannot be routed through `elfutil.NewFile`. `CheckAllSections` is that gate, and is deliberately named as the superset so the relationship to the narrow one is structural rather than documented. Also exports `ErrDeclaredSizeExceeded`. A refusal here costs the SBOM a package, so callers report it as an unknown, and matching on an error string to decide that is not something to build a reporting policy on. A ruleguard rule now flags `buildinfo.Read` and `version.ReadExeFromReader` outside `scan_binary.go`. Both open `debug/elf` internally and are only bounded there by the wrappers that gate the reader first, which the existing rule on `elf.NewFile` could not see through. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * feat(internal/spillbuf): sparse offset-addressed buffer that spills to disk For output that arrives out of order, at offsets the input itself declares: a decompressor placing extents, an archive rebuilding a file from chunks. A plain `[]byte` cannot do that without either pre-sizing to a length the input claims or growing to the furthest offset it names, and both hand a hostile input an allocation knob. The load-bearing property is that it reports only what it actually stored. `Size` is the contiguous run written from offset zero and a read past it is `io.EOF`, never the zeros an unwritten region would hand back for free. Sparse storage serving holes as real content is what lets a write offset stand in for output nothing produced, so anything sizing an allocation against this reader (`saferio` in `debug/elf` does exactly that) stays bounded by work actually done. `FirstGap` answers where the next write fits, so callers filling holes do not need the extent bookkeeping and cannot re-derive that rule wrongly, and it only reports gaps lying entirely inside `[0, within)`. The extent type is unexported for the same reason. The rest of the contract worth stating: reads and writes after `Close` fail with `os.ErrClosed` rather than looking like an empty buffer, and a write that fails leaves the buffer unchanged. Memory is bounded by the limit rather than by how much is written: filling 1MB and filling 64MB cost about the same. What lands on disk past that limit is the caller's bound to set, not this package's. Growth is geometric and capped, because sizing the tier to exactly what each write needs is quadratic once a caller streams through it in small chunks. The golang cataloger is the only consumer today, and nothing else in the tree has this shape. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * fix(golang): rebuild UPX binaries through spillbuf and read the reconstruction everywhere Two amplification paths were still reachable. A 128 byte input allocated 16MB by trusting `sz_cpr` before weighing it against the bytes the file actually holds, and the reconstruction was assembled in a `[]byte` sized from the header's declared original size, so a 301KB input allocated 300MB. The reconstruction is a `spillbuf.Buffer` now, which is what makes the second one go away: blocks are placed at the offsets the file declares, nothing is pre-sized from a claim, and the reader's length is the contiguous run actually rebuilt. That last part is the invariant everything downstream leans on. A reader reporting the declared size would serve the holes between placed blocks as zeros it never stored, and a 64 byte block parked at `p_filesize-64` then made a 300KB input hand out a 64MB reader: measured, that drove 269MB through `getBuildInfo` and returned nothing, silently. Placement and storage are separate concerns. `upx.go` places blocks at the offsets the file declares and asks the buffer how much was rebuilt and where the next gap is; it knows nothing about temp files or memory limits. The remaining bounds are ratios against the input wherever they can be, since an absolute ceiling only ever drops a large legitimate binary. The one absolute left is on `p_filesize`, because padding an input is nearly free, and the LZMA dictionary is paid for in its own block's `sz_cpr`. Interface change: `scanFile` takes a context and hands back the reconstruction for each binary that turned out to be packed, and the caller owns it. Everything after the build info read (crypto settings, arch, symbols, the version scan) reads it, so a packed binary no longer reports its packages with no symbols at all. Also narrows what gets reported. This cataloger runs on every executable in an image, so reporting every `getBuildInfo` error attached an unknown to every corrupt ELF, odd PE and non-Go Mach-O slice in it. Now only four gaps, the ones that cost the SBOM something syft could have had: a packed file we could not decode (`errUPXDecompress`), a header the size bounds refused (`errUPXSizeRefused`), a reconstruction that came up short (`errUPXPartial`), and an ELF expansion `elfutil` declined (`ErrDeclaredSizeExceeded`). An unimplemented UPX method stays quiet on purpose: `upx` defaults to NRV2B and only LZMA is implemented here, so reporting it would attach an unknown to most packed non-Go binaries in an image. That filtering is a new pattern. No other cataloger picks which of its errors become unknowns, and the reason this one does is that it runs on every executable in an image rather than on files a glob already selected. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * chore: ignore local spec/ planning notes `/specs` was already ignored; `/spec` is the same thing under the singular name and was not, so working notes landed in commits. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * refactor(golang): name what the unpack hands back, not where it stores it the scan's signatures said `*spillbuf.Buffer` all the way down, which told every reader below the scan that it cares whether the reconstruction lives in memory or on disk. it does not. two interfaces instead, each naming only what its side actually uses: - `unpackedContents` for the consumers: `ReaderAt`, `Closer`, and a `Size` that is the contiguous run rebuilt from zero - `blockSink` for the decoder, which additionally needs `WriterAt` and `FirstGap` to place blocks this costs one thing worth flagging. `Close` on a nil `*spillbuf.Buffer` was nil-safe, so callers just deferred it; widened into an interface, a nil pointer becomes a non-nil interface and the same call panics. `closeUnpacked` absorbs that, and it is now the only way an owner releases contents. `readerFor`, `seekerFor` and `closeUnpacked` are the three places that resolve the nil. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * docs(elfutil): say that CheckAllSections is the decompression-bomb gate the doc led with "bounds every section syft can drive debug/elf into decompressing", which describes the mechanism without ever naming what it is defending against. a reader landing on the call site could not tell that this is the decompression-bomb check. state the attack instead: a compressed section header declares its own decompressed size, debug/elf believes that number and allocates it on open, and nothing forces it to match what the compressed bytes actually yield. the 260KB ELF that drove 1.3GB of allocation now lives in the doc rather than only at the one call site that happened to mention it. comments only. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * docs(golang): move the overflow note onto the bounds test it describes the "subtraction form" note sat above the phStart assignment with ten lines of wrap analysis between it and the `if` it was talking about, so the subtraction it names reads as missing. it is `hdrLen-phStart < phentsize`. move it onto that test and name the form it is avoiding (`phStart+phentsize > hdrLen`, which can overflow past the buffer end) so the referent is not several paragraphs away. comments only. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> * chore(golang): drop the internal/ README left over from xcoff that README existed to record where the vendored xcoff package came from and that Go keeps it internal, which is a provenance note worth having while third-party code sat there. dropping xcoff took the reason with it, and repurposing it to point at gotestdata just made it redundant: gotestdata has its own README covering why it is under internal/, why it is not testdata/, and what belongs in each. internal/ now holds one self-documenting directory. Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com> --------- Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>
361 lines
15 KiB
Go
361 lines
15 KiB
Go
package golang
|
|
|
|
import (
|
|
"context"
|
|
"debug/buildinfo"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"runtime/debug"
|
|
"strings"
|
|
|
|
"github.com/kastenhq/goversion/version"
|
|
|
|
"github.com/anchore/syft/internal/log"
|
|
"github.com/anchore/syft/internal/unknown"
|
|
"github.com/anchore/syft/syft/file"
|
|
"github.com/anchore/syft/syft/internal/elfutil"
|
|
"github.com/anchore/syft/syft/internal/unionreader"
|
|
)
|
|
|
|
type extendedBuildInfo struct {
|
|
*debug.BuildInfo
|
|
cryptoSettings []string
|
|
arch string
|
|
symbols []binarySymbol
|
|
|
|
// unpacked is the reconstruction when this binary was UPX-packed, and nil when it was not. It is
|
|
// carried on the build info because the readers downstream of the scan want it too, since the packed
|
|
// bytes hold no readable version strings either. The caller of scanFile owns it and must Close it.
|
|
unpacked unpackedContents
|
|
}
|
|
|
|
// unpackedContents is the reconstruction of a UPX-packed binary, as everything downstream of the unpack
|
|
// uses it: bytes at offsets, the length it is willing to stand behind, and the temp file underneath to
|
|
// release when the scan is done with it. internal/spillbuf is what implements it, and naming that type in
|
|
// these signatures would say the readers care where the bytes live, which they do not.
|
|
//
|
|
// A nil value means the binary was not packed, and unpackUPX only ever returns a literal nil for that: a
|
|
// nil *spillbuf.Buffer widened into this interface is a non-nil interface holding a nil pointer, so it
|
|
// reads as present everywhere it is checked and then panics on first use. readerFor, seekerFor and
|
|
// closeUnpacked are the only places that check.
|
|
type unpackedContents interface {
|
|
io.ReaderAt
|
|
io.Closer
|
|
|
|
// Size is the contiguous run rebuilt from offset zero, which is all the reconstruction stands behind.
|
|
Size() int64
|
|
}
|
|
|
|
// scanFile scans file to try to report the Go and module versions.
|
|
func scanFile(ctx context.Context, location file.Location, reader unionreader.UnionReader, captureSymbols bool) ([]*extendedBuildInfo, error) {
|
|
// NOTE: multiple readers are returned to cover universal binaries, which are files
|
|
// with more than one binary
|
|
readers, errs := unionreader.GetReaders(reader)
|
|
if errs != nil {
|
|
log.WithFields("error", errs).Debug("failed to open a golang binary")
|
|
return nil, fmt.Errorf("failed to open a golang binary: %w", errs)
|
|
}
|
|
|
|
var builds []*extendedBuildInfo
|
|
for _, r := range readers {
|
|
build, err := scanReader(ctx, location, r, captureSymbols)
|
|
errs = unknown.Join(errs, err)
|
|
if build != nil {
|
|
builds = append(builds, build)
|
|
}
|
|
}
|
|
return builds, errs
|
|
}
|
|
|
|
// scanReader reports the build info, crypto settings, arch and symbols of a single binary. Everything is
|
|
// read from the same reader, which is the unpacked contents when the binary turns out to be UPX-packed:
|
|
// the packed bytes carry no readable pclntab or version strings either, so nothing downstream of the
|
|
// build info should be looking at them.
|
|
func scanReader(ctx context.Context, location file.Location, r io.ReaderAt, captureSymbols bool) (*extendedBuildInfo, error) {
|
|
var errs error
|
|
|
|
// unpacked is nil when there was nothing to unpack; readerFor turns that into the reader every parser
|
|
// below should use, so none of them has to ask whether this binary was packed.
|
|
// err can arrive alongside a usable bi: a partial reconstruction still carries build info, and the
|
|
// bytes it lost are a gap worth reporting rather than a reason to drop the binary.
|
|
unpacked, bi, err := readContentsAndBuildInfo(ctx, r)
|
|
|
|
// ownership of unpacked transfers to the returned extendedBuildInfo on success. Until then it is held
|
|
// here: the parsers below panic on malformed input (which is why getBuildInfo has a recover), and an
|
|
// unwind past this point would leave a reconstruction of up to maxUPXOriginalSize on disk for the rest
|
|
// of the scan: the temp root is swept, but not until the run ends.
|
|
ownContents := true
|
|
defer func() {
|
|
if ownContents {
|
|
closeUnpacked(unpacked)
|
|
}
|
|
}()
|
|
|
|
if err != nil {
|
|
if isCancelled(err) {
|
|
return nil, err
|
|
}
|
|
log.WithFields("file", location.RealPath, "error", err).Trace("unable to fully read golang buildinfo")
|
|
if reportableGap(err) {
|
|
// the build info is either missing or it is not, and the same err covers both: a partial
|
|
// reconstruction still hands back everything .go.buildinfo carried, and what it lost is the
|
|
// non-loadable tail the readers below want. Saying "unable to read golang buildinfo" there
|
|
// describes a failure that did not happen.
|
|
if bi != nil {
|
|
errs = unknown.Appendf(errs, location, "golang binary read incompletely: %w", err)
|
|
} else {
|
|
errs = unknown.Appendf(errs, location, "unable to read golang buildinfo: %w", err)
|
|
}
|
|
}
|
|
if bi == nil {
|
|
return nil, errs
|
|
}
|
|
}
|
|
|
|
// it's possible the reader just isn't a go binary, in which case just skip it
|
|
if bi == nil {
|
|
return nil, errs
|
|
}
|
|
|
|
// resolved once, here: every parser below reads the same bytes, and the choice of which reader that is
|
|
// belongs at the top rather than repeated at each call site
|
|
contents := readerFor(unpacked, r)
|
|
|
|
// everything below reads those contents through a parser that expands ELF sections, and each bounds its own
|
|
// reads: getSymbols opens the file with elfutil.NewFile, getCryptoInformation gates on
|
|
// elfutil.CheckAllSections. getBuildInfo's CheckSectionNameTable is not what makes these safe, since it
|
|
// bounds only the section elf.NewFile expands as it parses.
|
|
v, err := getCryptoInformation(contents)
|
|
if err != nil {
|
|
log.WithFields("file", location.RealPath, "error", err).Trace("unable to read golang version info")
|
|
// don't skip this build info.
|
|
// we can still catalog packages, even if we can't get the crypto information
|
|
errs = unknown.Appendf(errs, location, "unable to read golang version info: %w", err)
|
|
}
|
|
v = append(v, getNativeFIPSSettings(bi.Settings)...)
|
|
arch := getGOARCH(bi.Settings)
|
|
if arch == "" {
|
|
arch, err = getGOARCHFromBin(contents)
|
|
if err != nil {
|
|
log.WithFields("file", location.RealPath, "error", err).Trace("unable to read golang arch info")
|
|
// don't skip this build info.
|
|
// we can still catalog packages, even if we can't get the arch information
|
|
errs = unknown.Appendf(errs, location, "unable to read golang arch info: %w", err)
|
|
}
|
|
}
|
|
|
|
var symbols []binarySymbol
|
|
if captureSymbols {
|
|
symbols, err = getSymbols(contents)
|
|
if err != nil {
|
|
log.WithFields("file", location.RealPath, "error", err).Trace("unable to read golang symbol info")
|
|
// don't skip this build info.
|
|
// we can still catalog packages, even if we can't get the symbol information
|
|
errs = unknown.Appendf(errs, location, "unable to read golang symbol info: %w", err)
|
|
}
|
|
}
|
|
|
|
ownContents = false
|
|
return &extendedBuildInfo{BuildInfo: bi, cryptoSettings: v, arch: arch, symbols: symbols, unpacked: unpacked}, errs
|
|
}
|
|
|
|
// reportableGap reports whether err is a gap this cataloger chose to leave, rather than a file it was
|
|
// never going to catalog. A packed file we failed to decode, a reconstruction that came up short, and a
|
|
// file we declined to expand (from either the ELF section bound or the UPX header bounds) all cost the
|
|
// SBOM something real. This cataloger runs on every executable in an image, so reporting anything else
|
|
// would attach an unknown to every corrupt, truncated or non-Go binary in it, which is the noise the
|
|
// quiet-by-default policy in upx.go exists to avoid.
|
|
//
|
|
// One real gap is deliberately left off this list: a UPX method we have not implemented. It is the same
|
|
// cost to the SBOM as a decode failure, but it fires on most packed binaries rather than on rare ones.
|
|
// See errUPXDecompress in upx.go for the reasoning.
|
|
func reportableGap(err error) bool {
|
|
return errors.Is(err, errUPXDecompress) ||
|
|
errors.Is(err, errUPXSizeRefused) ||
|
|
errors.Is(err, errUPXPartial) ||
|
|
errors.Is(err, elfutil.ErrDeclaredSizeExceeded)
|
|
}
|
|
|
|
func getCryptoInformation(reader io.ReaderAt) ([]string, error) {
|
|
// goversion opens the file with debug/elf itself and reads .symtab plus the string table it links.
|
|
// Those are expanded lazily, so the section-name table bound getBuildInfo already applied does not
|
|
// reach them. CheckAllSections is the decompression-bomb gate: a compressed section declares its own
|
|
// decompressed size and debug/elf allocates that much on open, so a 260KB ELF declaring a compressed
|
|
// .symtab drove 1.3GB of allocation before this was here.
|
|
if err := elfutil.CheckAllSections(reader); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
v, err := version.ReadExeFromReader(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return getCryptoSettingsFromVersion(v), nil
|
|
}
|
|
|
|
func getCryptoSettingsFromVersion(v version.Version) []string {
|
|
cryptoSettings := []string{}
|
|
if v.StandardCrypto {
|
|
cryptoSettings = append(cryptoSettings, "standard-crypto")
|
|
}
|
|
if v.BoringCrypto {
|
|
cryptoSettings = append(cryptoSettings, "boring-crypto")
|
|
}
|
|
if v.FIPSOnly {
|
|
cryptoSettings = append(cryptoSettings, "crypto/tls/fipsonly")
|
|
}
|
|
return cryptoSettings
|
|
}
|
|
|
|
func getNativeFIPSSettings(settings []debug.BuildSetting) []string {
|
|
var cryptoSettings []string
|
|
for _, s := range settings {
|
|
switch s.Key {
|
|
case "GOFIPS140":
|
|
if s.Value != "" {
|
|
cryptoSettings = append(cryptoSettings, "GOFIPS140="+s.Value)
|
|
}
|
|
case "DefaultGODEBUG":
|
|
for _, kv := range strings.Split(s.Value, ",") {
|
|
if setting, val, ok := strings.Cut(kv, "="); ok && setting == "fips140" {
|
|
cryptoSettings = append(cryptoSettings, "GODEBUG=fips140="+val)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return cryptoSettings
|
|
}
|
|
|
|
// readContentsAndBuildInfo returns the contents this binary should be read from, along with its build
|
|
// info. A UPX-packed binary is unpacked first and read from the reconstruction.
|
|
//
|
|
// If the reconstruction carries no build info, the bytes as they were found are tried before giving up.
|
|
// The "UPX!" magic is located by an unanchored scan over the first 8KB and every field behind it is
|
|
// attacker-controlled, so an ordinary Go binary carrying those four bytes can be made to produce a
|
|
// plausible header and a reconstruction of nothing. Without the retry that binary reports no packages at
|
|
// all, which turns a false positive here into a way to hide a dependency list.
|
|
//
|
|
// A gap in the unpack is returned even when build info came through, so it is reported rather than papered
|
|
// over: the readers after this one (crypto settings, arch, symbols) read the same contents, and the bytes
|
|
// a partial reconstruction lost are exactly the non-loadable tail those depend on. That only holds when
|
|
// the contents are a reconstruction: a gap read off the bytes as they were found is not a gap at all, and
|
|
// both places below that hand those bytes back drop it.
|
|
func readContentsAndBuildInfo(ctx context.Context, r io.ReaderAt) (unpackedContents, *debug.BuildInfo, error) {
|
|
unpacked, unpackErr := unpackUPX(ctx, r)
|
|
if isCancelled(unpackErr) {
|
|
return unpacked, nil, unpackErr
|
|
}
|
|
|
|
bi, err := getBuildInfo(readerFor(unpacked, r))
|
|
if err == nil && bi != nil {
|
|
if unpacked == nil {
|
|
// nothing was rebuilt, so nothing downstream is short: every reader below this one reads the
|
|
// same bytes getBuildInfo just read in full. unpackUPX returns the input as it was found
|
|
// alongside a refusal (the size bounds) or a failure (block 1 not decoding, or no temp dir),
|
|
// and readable build info in those bytes is itself the evidence the file was not really
|
|
// packed. A genuinely packed binary carries no readable .go.buildinfo in its packed bytes, so
|
|
// it never reaches here and its gap is still reported below.
|
|
return unpacked, bi, nil
|
|
}
|
|
return unpacked, bi, unpackErr
|
|
}
|
|
|
|
if unpacked != nil {
|
|
if foundBI, foundErr := getBuildInfo(r); foundErr == nil && foundBI != nil {
|
|
log.WithFields("error", err, "unpackError", unpackErr).
|
|
Trace("UPX reconstruction carried no build info, reading the binary as it was found")
|
|
closeUnpacked(unpacked)
|
|
// unpackErr is deliberately dropped. Every reader after this one reads the bytes as they were
|
|
// found, not the reconstruction, so nothing downstream is short: the header this binary
|
|
// carried was not describing real UPX output in the first place. Returning the gap here would
|
|
// put an unknown on a binary the cataloger read completely.
|
|
return nil, foundBI, nil
|
|
}
|
|
}
|
|
|
|
// a packed file we could not unpack is the more specific gap, so it wins over whatever buildinfo made
|
|
// of the bytes it was handed
|
|
if unpackErr != nil {
|
|
return unpacked, nil, unpackErr
|
|
}
|
|
return unpacked, bi, err
|
|
}
|
|
|
|
// isCancelled reports whether err means the scan was called off, which is a reason to stop rather than a
|
|
// gap in the SBOM.
|
|
func isCancelled(err error) bool {
|
|
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
|
|
}
|
|
|
|
// readerFor returns where a scanned binary should be read from: the reconstruction when it was packed,
|
|
// the input as it was found otherwise.
|
|
//
|
|
// The nil check lives here, in one place, on purpose: every reader below the scan goes through here, so no
|
|
// parser has to ask whether this binary was packed.
|
|
func readerFor(unpacked unpackedContents, found io.ReaderAt) io.ReaderAt {
|
|
if unpacked == nil {
|
|
return found
|
|
}
|
|
return unpacked
|
|
}
|
|
|
|
// seekerFor is readerFor for the readers after the scan, which seek. found belongs to the caller and is
|
|
// reused for every later module, so this deliberately hands back no Closer.
|
|
func seekerFor(unpacked unpackedContents, found io.ReadSeeker) io.ReadSeeker {
|
|
if unpacked == nil {
|
|
return found
|
|
}
|
|
// the SectionReader snapshots Size() here, which is correct: the reconstruction is complete by the time
|
|
// anything seeks it. It also gives each caller its own cursor over the same contents.
|
|
return io.NewSectionReader(unpacked, 0, unpacked.Size())
|
|
}
|
|
|
|
// closeUnpacked releases a reconstruction, if the binary turned out to be packed at all. Nothing to unpack
|
|
// is the common case rather than an edge one, so every owner of an unpackedContents closes through here.
|
|
func closeUnpacked(unpacked unpackedContents) {
|
|
if unpacked == nil {
|
|
return
|
|
}
|
|
_ = unpacked.Close()
|
|
}
|
|
|
|
// readBuildInfo bounds the reader before handing it to debug/buildinfo, which opens ELF files with
|
|
// debug/elf itself rather than through elfutil. elf.NewFile expands the section-name string table as it
|
|
// parses, so an unbounded read here is reachable no matter how little of the file buildinfo goes on to
|
|
// look at.
|
|
func readBuildInfo(r io.ReaderAt) (*debug.BuildInfo, error) {
|
|
if err := elfutil.CheckSectionNameTable(r); err != nil {
|
|
return nil, err
|
|
}
|
|
return buildinfo.Read(r)
|
|
}
|
|
|
|
func getBuildInfo(r io.ReaderAt) (bi *debug.BuildInfo, err error) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
// this can happen in cases where a malformed binary is passed in can be initially parsed, but not
|
|
// used without error later down the line. This is the case with :
|
|
// https://github.com/llvm/llvm-project/blob/llvmorg-15.0.6/llvm/test/Object/Inputs/macho-invalid-dysymtab-bad-size
|
|
err = fmt.Errorf("recovered from panic: %v", r)
|
|
}
|
|
}()
|
|
|
|
bi, err = readBuildInfo(r)
|
|
|
|
// note: the stdlib does not export the error we need to check for
|
|
if err != nil {
|
|
if err.Error() == "not a Go executable" {
|
|
// since the cataloger can only select executables and not distinguish if they are a go-compiled
|
|
// binary, we should not show warnings/logs in this case. For this reason we nil-out err here.
|
|
err = nil
|
|
return bi, err
|
|
}
|
|
// in this case we could not read the or parse the file, but not explicitly because it is not a
|
|
// go-compiled binary (though it still might be).
|
|
return bi, err
|
|
}
|
|
return bi, err
|
|
}
|