Path: blob/main/components/ee/agent-smith/pkg/classifier/signature_test.go
2501 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package classifier56import (7"bytes"8"os"9"testing"1011"github.com/h2non/filetype"12"github.com/h2non/filetype/matchers"13)1415func TestMatchELF(t *testing.T) {16exec := "/bin/bash"17input, err := os.OpenFile(exec, os.O_RDONLY, 0600)18if err != nil {19t.Errorf("cannot open test executable: %v", err)20return21}22defer input.Close()2324sfc := SignatureReadCache{25Reader: input,26}2728sig := Signature{29Kind: ObjectELFSymbols,30Pattern: []byte("bash_groupname_completion_function"),31Regexp: false,32}33if err := sig.Validate(); err != nil {34t.Errorf("invalid signature: %v", err)35return36}3738matches, err := sig.Matches(&sfc)39if err != nil {40t.Errorf("cannot match signature: %v", err)41return42}43if !matches {44t.Errorf("%s does not match signature", exec)45}46}4748func TestMatchAny(t *testing.T) {49tests := []struct {50Input []byte51Signature Signature52Matches bool53Err error54}{55{[]byte("hello world!!"), Signature{Kind: ObjectAny, Pattern: []byte("o w")}, true, nil},56{[]byte("abab dede"), Signature{Kind: ObjectAny, Pattern: []byte("ab"), Slice: Slice{5, 0}}, false, nil},57{[]byte("abab dede"), Signature{Kind: ObjectAny, Pattern: []byte("de"), Slice: Slice{5, 0}}, true, nil},58}5960for i, test := range tests {61if err := test.Signature.Validate(); err != nil {62t.Errorf("[%03d] invalid signature: %v", i, err)63return64}6566sfc := SignatureReadCache{67Reader: bytes.NewReader(test.Input),68}6970matches, err := test.Signature.matchAny(&sfc)71if err != nil {72t.Errorf("[%03d] cannot match signature: %v", i, err)73return74}75if matches != test.Matches {76t.Errorf("[%03d] expected match == %v, actual is %v", i, test.Matches, matches)77}78}79}8081func TestIsELF(t *testing.T) {82tests := []struct {83Name string84Input []byte85}{86{"ELF", []byte{0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},87{"JPEG2000", []byte{0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A}},88{"too short", []byte{}},89}9091for _, test := range tests {92// test our input against a known library to make sure we actually have an ELF binary on our hands93isActuallyELF := filetype.IsType(test.Input, matchers.TypeElf)94weThinkItsELF := isELF(test.Input)9596if weThinkItsELF != isActuallyELF {97t.Errorf("%s: input does not test as same ELF-ness as gold standard. %v expected, %v actual", test.Name, isActuallyELF, weThinkItsELF)98}99}100}101102103