Skip to content

Commit

Permalink
[Auditbeat] File Integrity ECS update (#18012)
Browse files Browse the repository at this point in the history
* Add extension, mime_type and drive_letter

* run go mod vendor

* Add ECS categorization fields

* mage fmt

* Update hash and NOTICE

* Update test

* Run mage vendor

* Add changelog entry

* Extract isASCIILetter

* switch over to godoc style comment
  • Loading branch information
Andrew Stucki committed May 5, 2020
1 parent 5d66251 commit 56ba9d0
Show file tree
Hide file tree
Showing 35 changed files with 2,020 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.next.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD d
- Add system module package dataset ECS categorization fields. {pull}18033[18033]
- Add system module login dataset ECS categorization fields. {pull}18034[18034]
- Add system module user dataset ECS categorization fields. {pull}18035[18035]
- Add file integrity module ECS categorization fields. {pull}18012[18012]
- Add `file.mime_type`, `file.extension`, and `file.drive_letter` for file integrity module. {pull}18012[18012]

*Filebeat*

Expand Down
31 changes: 31 additions & 0 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3261,6 +3261,37 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

--------------------------------------------------------------------
Dependency: github.com/h2non/filetype
Version: v1.0.12
License type (autodetected): MIT
./vendor/github.com/h2non/filetype/LICENSE:
--------------------------------------------------------------------
The MIT License

Copyright (c) Tomas Aparicio

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

--------------------------------------------------------------------
Dependency: github.com/hashicorp/errwrap
Version: v1.0.0
Expand Down
39 changes: 39 additions & 0 deletions auditbeat/module/file_integrity/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ package file_integrity
import (
"math/bits"
"strings"

"github.com/elastic/beats/v7/libbeat/common"
)

// Action is a description of the changes described by an event.
Expand Down Expand Up @@ -51,6 +53,17 @@ var actionNames = map[Action]string{
InitialScan: "initial_scan",
}

var ecsActionNames = map[Action]string{
None: "info",
AttributesModified: "change",
Created: "creation",
Deleted: "deletion",
Updated: "change",
Moved: "change",
ConfigChange: "change",
InitialScan: "info",
}

type actionOrderKey struct {
ExistsBefore, ExistsNow bool
Action Action
Expand Down Expand Up @@ -102,6 +115,22 @@ func (action Action) String() string {
return strings.Join(list, "|")
}

// ECSTypes returns the ECS categorization types associated with the
// particular action.
func (action Action) ECSTypes() []string {
if name, found := ecsActionNames[action]; found {
return []string{name}
}
var list []string
for flag, name := range ecsActionNames {
if action&flag != 0 {
action ^= flag
list = append(list, name)
}
}
return common.MakeStringSet(list...).ToSlice()
}

// MarshalText marshals the Action to a textual representation of itself.
func (action Action) MarshalText() ([]byte, error) { return []byte(action.String()), nil }

Expand Down Expand Up @@ -174,3 +203,13 @@ func (actions ActionArray) StringArray() []string {
}
return result
}

// ECSTypes returns the array of ECS categorization types for
// the set of actions.
func (actions ActionArray) ECSTypes() []string {
var list []string
for _, action := range actions {
list = append(list, action.ECSTypes()...)
}
return common.MakeStringSet(list...).ToSlice()
}
39 changes: 37 additions & 2 deletions auditbeat/module/file_integrity/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"path/filepath"
"runtime"
"strconv"
"strings"
"time"

"github.com/cespare/xxhash/v2"
Expand Down Expand Up @@ -214,6 +215,24 @@ func NewEvent(
return NewEventFromFileInfo(path, info, err, action, source, maxFileSize, hashTypes)
}

func isASCIILetter(letter byte) bool {
// It appears that Windows only allows ascii characters for drive letters
// and that's what go checks for: https://golang.org/src/path/filepath/path_windows.go#L63
// **If** Windows/go ever return multibyte utf16 characters we'll need to change
// the drive letter mapping logic.
return (letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z')
}

func getDriveLetter(path string) string {
volume := filepath.VolumeName(path)
if len(volume) == 2 && volume[1] == ':' {
if isASCIILetter(volume[0]) {
return strings.ToUpper(volume[:1])
}
}
return ""
}

func buildMetricbeatEvent(e *Event, existedBefore bool) mb.Event {
file := common.MapStr{
"path": e.Path,
Expand All @@ -237,6 +256,12 @@ func buildMetricbeatEvent(e *Event, existedBefore bool) mb.Event {
file["ctime"] = info.CTime

if e.Info.Type == FileType {
if extension := filepath.Ext(e.Path); extension != "" {
file["extension"] = extension
}
if mimeType := getMimeType(e.Path); mimeType != "" {
file["mime_type"] = mimeType
}
file["size"] = info.Size
}

Expand All @@ -245,6 +270,9 @@ func buildMetricbeatEvent(e *Event, existedBefore bool) mb.Event {
}

if runtime.GOOS == "windows" {
if drive := getDriveLetter(e.Path); drive != "" {
file["drive_letter"] = drive
}
if info.SID != "" {
file["uid"] = info.SID
}
Expand Down Expand Up @@ -276,12 +304,19 @@ func buildMetricbeatEvent(e *Event, existedBefore bool) mb.Event {
for hashType, digest := range e.Hashes {
hashes[string(hashType)] = digest
}
file["hash"] = hashes
// Remove this for 8.x
out.MetricSetFields.Put("hash", hashes)
}

out.MetricSetFields.Put("event.kind", "event")
out.MetricSetFields.Put("event.category", []string{"file"})
if e.Action > 0 {
actions := e.Action.InOrder(existedBefore, e.Info != nil).StringArray()
out.MetricSetFields.Put("event.action", actions)
actions := e.Action.InOrder(existedBefore, e.Info != nil)
out.MetricSetFields.Put("event.type", actions.ECSTypes())
out.MetricSetFields.Put("event.action", actions.StringArray())
} else {
out.MetricSetFields.Put("event.type", None.ECSTypes())
}

return out
Expand Down
48 changes: 47 additions & 1 deletion auditbeat/module/file_integrity/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ var testEventTime = time.Now().UTC()
func testEvent() *Event {
return &Event{
Timestamp: testEventTime,
Path: "/home/user",
Path: "/home/user/file.txt",
Source: SourceScan,
Action: ConfigChange,
Info: &Metadata{
Expand Down Expand Up @@ -290,8 +290,12 @@ func TestBuildEvent(t *testing.T) {
assert.Equal(t, testEventTime, e.Timestamp)

assertHasKey(t, fields, "event.action")
assertHasKey(t, fields, "event.kind")
assertHasKey(t, fields, "event.category")
assertHasKey(t, fields, "event.type")

assertHasKey(t, fields, "file.path")
assertHasKey(t, fields, "file.extension")
assertHasKey(t, fields, "file.target_path")
assertHasKey(t, fields, "file.inode")
assertHasKey(t, fields, "file.uid")
Expand All @@ -309,9 +313,51 @@ func TestBuildEvent(t *testing.T) {
assertHasKey(t, fields, "file.mode")
}

assertHasKey(t, fields, "file.hash.sha1")
assertHasKey(t, fields, "file.hash.sha256")
// Remove in 8.x
assertHasKey(t, fields, "hash.sha1")
assertHasKey(t, fields, "hash.sha256")
})
if runtime.GOOS == "windows" {
t.Run("drive letter", func(t *testing.T) {
e := testEvent()
e.Path = "c:\\Documents"
fields := buildMetricbeatEvent(e, false).MetricSetFields
value, err := fields.GetValue("file.drive_letter")
assert.NoError(t, err)
assert.Equal(t, "C", value)
})
t.Run("no drive letter", func(t *testing.T) {
e := testEvent()
e.Path = "\\\\remote\\Documents"
fields := buildMetricbeatEvent(e, false).MetricSetFields
_, err := fields.GetValue("file.drive_letter")
assert.Error(t, err)
})
}
t.Run("ecs categorization", func(t *testing.T) {
e := testEvent()
e.Action = ConfigChange
fields := buildMetricbeatEvent(e, false).MetricSetFields
types, err := fields.GetValue("event.type")
if err != nil {
t.Fatal(err)
}
ecsTypes, ok := types.([]string)
assert.True(t, ok)
assert.Equal(t, []string{"change"}, ecsTypes)

e.Action = Action(Created | Updated | Deleted)
fields = buildMetricbeatEvent(e, false).MetricSetFields
types, err = fields.GetValue("event.type")
if err != nil {
t.Fatal(err)
}
ecsTypes, ok = types.([]string)
assert.True(t, ok)
assert.Equal(t, []string{"change", "creation", "deletion"}, ecsTypes)
})
t.Run("no setuid/setgid", func(t *testing.T) {
e := testEvent()
e.Info.SetGID = false
Expand Down
53 changes: 53 additions & 0 deletions auditbeat/module/file_integrity/mime.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package file_integrity

import (
"github.com/h2non/filetype"

"github.com/elastic/beats/v7/libbeat/common/file"
)

const (
// Size for mime detection, office file
// detection requires ~8kb to detect properly
headerSize = 8192
)

// getMimeType does a best-effort to get the file type, if no
// filetype can be determined, it just returns an empty
// string
func getMimeType(path string) string {
f, err := file.ReadOpen(path)
if err != nil {
return ""
}
defer f.Close()

head := make([]byte, headerSize)
n, err := f.Read(head)
if err != nil {
return ""
}

kind, err := filetype.Match(head[:n])
if err != nil {
return ""
}
return kind.MIME.Value
}
68 changes: 68 additions & 0 deletions auditbeat/module/file_integrity/mime_test.go

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ require (
github.com/gorilla/mux v1.7.2 // indirect
github.com/gorilla/websocket v1.4.1 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.13.0 // indirect
github.com/h2non/filetype v1.0.12
github.com/hashicorp/go-multierror v1.0.0
github.com/hashicorp/golang-lru v0.5.2-0.20190520140433-59383c442f7d // indirect
github.com/insomniacslk/dhcp v0.0.0-20180716145214-633285ba52b2
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,9 @@ github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/ad
github.com/gregjones/httpcache v0.0.0-20170728041850-787624de3eb7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/grpc-ecosystem/grpc-gateway v1.13.0 h1:sBDQoHXrOlfPobnKw69FIKa1wg9qsLLvvQ/Y19WtFgI=
github.com/grpc-ecosystem/grpc-gateway v1.13.0/go.mod h1:8XEsbTttt/W+VvjtQhLACqCisSPWTxCZ7sBRjU6iH9c=
github.com/h2non/filetype v1.0.12 h1:yHCsIe0y2cvbDARtJhGBTD2ecvqMSTvlIcph9En/Zao=
github.com/h2non/filetype v1.0.12/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce h1:prjrVgOk2Yg6w+PflHoszQNLTUh4kaByUcEWM/9uin4=
github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
Expand Down
12 changes: 12 additions & 0 deletions vendor/github.com/h2non/filetype/.editorconfig

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions vendor/github.com/h2non/filetype/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions vendor/github.com/h2non/filetype/.travis.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 56ba9d0

Please sign in to comment.