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

[Auditbeat] File Integrity ECS update #18012

Merged
merged 12 commits into from
May 5, 2020
Merged
Show file tree
Hide file tree
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
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)
andrewstucki marked this conversation as resolved.
Show resolved Hide resolved
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")
andrewstucki marked this conversation as resolved.
Show resolved Hide resolved
})
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