Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter out noise opening non-ELF files #811

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions pkg/linter/linter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package linter

import (
"bytes"
"context"
"debug/elf"
"fmt"
Expand Down Expand Up @@ -293,6 +294,8 @@ func worldWriteableLinter(_ LinterContext, path string, d fs.DirEntry) error {
return nil
}

var elfMagic = []byte{'\x7f', 'E', 'L', 'F'}

func strippedLinter(lctx LinterContext, path string, d fs.DirEntry) error {
if isIgnoredPath(path) {
return nil
Expand All @@ -308,6 +311,11 @@ func strippedLinter(lctx LinterContext, path string, d fs.DirEntry) error {
return err
}

if info.Size() < int64(len(elfMagic)) {
// This is definitely not an ELF file.
return nil
}

ext := filepath.Ext(path)
mode := info.Mode()
if mode&0111 == 0 && !isObjectFileRegex.MatchString(ext) {
Expand All @@ -317,28 +325,37 @@ func strippedLinter(lctx LinterContext, path string, d fs.DirEntry) error {

f, err := lctx.fsys.Open(path)
if err != nil {
return fmt.Errorf("Could not open file for reading: %v", err)
return fmt.Errorf("opening file: %w", err)
}
defer f.Close()

// Both os.DirFS and go-apk return a file that implements ReaderAt.
// We don't have any other callers, so this should never fail.
readerAt, ok := f.(io.ReaderAt)
if !ok {
return fmt.Errorf("file does not impl ReaderAt: %T", f)
return fmt.Errorf("fs.File does not impl ReaderAt: %T", f)
}

hdr := make([]byte, len(elfMagic))
if _, err := readerAt.ReadAt(hdr, 0); err != nil {
return fmt.Errorf("failed to read %d bytes for magic ELF header: %w", len(elfMagic), err)
}

if !bytes.Equal(elfMagic, hdr) {
// No magic header, definitely not ELF.
return nil
}

file, err := elf.NewFile(readerAt)
if err != nil {
// We don't particularly care if this fails, it means it's probably not an ELF file
// We don't particularly care if this fails otherwise.
fmt.Printf("WARNING: Could not open file %q as executable: %v\n", path, err)
return nil
}
defer file.Close()

// No debug sections allowed
if file.Section(".debug") != nil || file.Section(".zdebug") != nil {
return fmt.Errorf("File is not stripped")
return fmt.Errorf("ELF file is not stripped")
}

return nil
Expand Down
Loading