Skip to content

Commit

Permalink
Add timezone config option to decode_cef
Browse files Browse the repository at this point in the history
CEF message that contain timestamps without a timezone were parsed as UTC. The time zone was not
configurable. This adds a `timezone` option to the decode_cef processor and cef module to allow the
time zone to be specified when a timestamp does not contain an offset or zone.

    CEF:0|Aruba Networks|ClearPass|6.8.7.120583|2002|RADIUS Accounting|1|rt=Aug 04 2021 11:31:15

Note that the CEF module receives messages using the syslog input. The syslog input does not have
a configurable time zone and always assumes timestamps without time zones are given in the machine's
local time zone. This change won't affect how the syslog envelop's time stamp is parsed by the module.

This also replaces the deprecated `import "4d63.com/tz"` with Go's relatively new built-in
`time/tzdata` package. The `timestamp` processor was updated.

Fixes #27232
  • Loading branch information
andrewkroh committed Sep 3, 2021
1 parent d6f899e commit c47f3c9
Show file tree
Hide file tree
Showing 23 changed files with 259 additions and 153 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.next.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,7 @@ https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD d
- Add support to merge registry updates in the filestream input across multiple ACKed batches in case of backpressure in the registry or disk. {pull}25976[25976]
- Add support to `decode_cef` for MAC addresses that do not contain separator characters. {issue}27050[27050] {pull}27109[27109]
- Add new `hmac` template function for httpjson input {pull}27168[27168]
- Add `timezone` config option to the `decode_cef` processor. {issue}27232[27232] {pull}27727[27727]
- Update `tags` and `threatintel.indicator.provider` fields in `threatintel.anomali` ingest pipeline {issue}24746[24746] {pull}27141[27141]
- Move AWS module and filesets to GA. {pull}27428[27428]
- update ecs.version to ECS 1.11.0. {pull}27107[27107]
Expand Down
92 changes: 0 additions & 92 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,69 +9,6 @@ Third party libraries used by the Elastic Beats project:
================================================================================


--------------------------------------------------------------------------------
Dependency : 4d63.com/tz
Version: v1.1.1-0.20191124060701-6d37baae851b
Licence type (autodetected): MIT
--------------------------------------------------------------------------------

Contents of probable licence file $GOMODCACHE/4d63.com/[email protected]/LICENSE:

MIT License

Copyright (c) 2018 Leigh McCulloch

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.

--------------------------------------------------------------------------------

zoneinfo.go generated from /lib/time/zoneinfo.zip from Go.

Copyright (c) 2009 The Go Authors. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 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 : cloud.google.com/go
Version: v0.51.0
Expand Down Expand Up @@ -19369,35 +19306,6 @@ Contents of probable licence file $GOMODCACHE/k8s.io/[email protected]/LICENSE:
Indirect dependencies


--------------------------------------------------------------------------------
Dependency : 4d63.com/embedfiles
Version: v0.0.0-20190311033909-995e0740726f
Licence type (autodetected): MIT
--------------------------------------------------------------------------------

Contents of probable licence file $GOMODCACHE/4d63.com/[email protected]/LICENSE:

Copyright (c) 2017, Leigh McCulloch

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 : bazil.org/fuse
Version: v0.0.0-20160811212531-371fbbdaa898
Expand Down
7 changes: 7 additions & 0 deletions filebeat/docs/modules/cef.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ A list of tags to include in events. Including `forwarded` indicates that the
events did not originate on this host and causes `host.name` to not be added to
events. Defaults to `[cef, forwarded]`.

*`var.timezone`*::

IANA time zone name (e.g. `America/New_York`) or fixed time offset (e.g.
`+0200`) to use when parsing times from the CEF message that do not contain a
time zone. `Local` may be specified to use the machine's local time zone.
Defaults to `UTC`.

[float]
==== Forcepoint NGFW Security Management Center

Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ module github.com/elastic/beats/v7
go 1.16

require (
4d63.com/tz v1.1.1-0.20191124060701-6d37baae851b
cloud.google.com/go v0.51.0
cloud.google.com/go/bigquery v1.0.1
cloud.google.com/go/pubsub v1.0.1
Expand Down
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
4d63.com/embedfiles v0.0.0-20190311033909-995e0740726f h1:oyYjGRBNq1TxAIG8aHqtxlvqUfzdZf+MbcRb/oweNfY=
4d63.com/embedfiles v0.0.0-20190311033909-995e0740726f/go.mod h1:HxEsUxoVZyRxsZML/S6e2xAuieFMlGO0756ncWx1aXE=
4d63.com/tz v1.1.1-0.20191124060701-6d37baae851b h1:+TO4EgK74+Qo/ilRDiF2WpY09Jk9VSJSLe3wEn+dJBw=
4d63.com/tz v1.1.1-0.20191124060701-6d37baae851b/go.mod h1:SHGqVdL7hd2ZaX2T9uEiOZ/OFAUfCCLURdLPJsd8ZNs=
bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8=
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
Expand Down
94 changes: 94 additions & 0 deletions libbeat/common/cfgtype/timezone.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// 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 cfgtype

import (
"encoding/json"
"time"

"github.com/pkg/errors"

// Embed the timezone database so this code works across platforms.
_ "time/tzdata"
)

var fixedOffsetFormats = []string{"-07", "-0700", "-07:00"}

// Timezone maps time instants to the zone in use at that time. Typically, the
// Timezone represents the collection of time offsets in use in a geographical
// area. For many Locations the time offset varies depending on whether daylight
// savings time is in use at the time instant.
type Timezone time.Location

// NewTimezone returns a new timezone.
func NewTimezone(tz string) (*Timezone, error) {
loc, err := loadLocation(tz)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse timezone %q", tz)
}
return (*Timezone)(loc), nil
}

// MustNewTimezone returns a new timezone. If tz is invalid it panics.
func MustNewTimezone(tz string) *Timezone {
timestamp, err := NewTimezone(tz)
if err != nil {
panic(err)
}
return timestamp
}

// Location returns a *time.Location. If timezone is nil it returns *time.UTC.
func (tz *Timezone) Location() *time.Location {
if tz == nil {
return time.UTC
}
return (*time.Location)(tz)
}

// MarshalJSON implements json.Marshaler interface.
func (tz *Timezone) MarshalJSON() ([]byte, error) {
if tz == nil {
return []byte("null"), nil
}
return json.Marshal(tz.Location().String())
}

// Unpack converts a time zone name or offset to Timezone. If using a fixed
// offset then the format must be [+-]HHMM (e.g +0800 or -0530).
func (tz *Timezone) Unpack(v string) error {
timezone, err := NewTimezone(v)
if err != nil {
return err
}
*tz = *timezone
return nil
}

func loadLocation(timezone string) (*time.Location, error) {
for _, format := range fixedOffsetFormats {
t, err := time.Parse(format, timezone)
if err == nil {
name, offset := t.Zone()
return time.FixedZone(name, offset), nil
}
}

// Handle IANA time zones.
return time.LoadLocation(timezone)
}
63 changes: 63 additions & 0 deletions libbeat/common/cfgtype/timezone_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// 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 cfgtype

import (
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestTimezoneUnpack(t *testing.T) {
testCases := []struct {
ZoneName string
}{
{"America/New_York"},
{"Local"},
{"+0500"},
{"-0500"},
{"+05:00"},
{"-05:00"},
{"+05"},
{"-05"},
{"UTC"},
}

for _, tc := range testCases {
t.Run(tc.ZoneName, func(t *testing.T) {
tz := &Timezone{}
err := tz.Unpack(tc.ZoneName)
require.NoError(t, err)
})
}
}

func TestTimezoneUnpackFixedZone(t *testing.T) {
tz := &Timezone{}
err := tz.Unpack("+0530")
require.NoError(t, err)

now := time.Time{}
loc := tz.Location()
offset := now.In(loc)
offsetHour := offset.Hour()
offsetMinute := offset.Minute()
require.Equal(t, 5, offsetHour)
require.Equal(t, 30, offsetMinute)
}
2 changes: 1 addition & 1 deletion libbeat/common/datetime.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func ParseTime(timespec string) (Time, error) {
}

func (t Time) String() string {
return time.Time(t).Format(TsLayout)
return time.Time(t).UTC().Format(TsLayout)
}

// MustParseTime is a convenience equivalent of the ParseTime function
Expand Down
18 changes: 10 additions & 8 deletions libbeat/processors/timestamp/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,17 @@

package timestamp

import "github.com/elastic/beats/v7/libbeat/common/cfgtype"

type config struct {
Field string `config:"field" validate:"required"` // Source field containing time time to be parsed.
TargetField string `config:"target_field"` // Target field for the parsed time value. The target value is always written as UTC. Defaults to @timestamp.
Layouts []string `config:"layouts" validate:"required"` // Timestamp layouts that define the expected time value format.
Timezone string `config:"timezone"` // Timezone (e.g. America/New_York) to use when parsing a timestamp not containing a timezone.
IgnoreMissing bool `config:"ignore_missing"` // Ignore errors when the source field is missing.
IgnoreFailure bool `config:"ignore_failure"` // Ignore errors when parsing the timestamp.
TestTimestamps []string `config:"test"` // A list of timestamps that must parse successfully when loading the processor.
ID string `config:"id"` // An identifier for this processor. Useful for debugging.
Field string `config:"field" validate:"required"` // Source field containing time time to be parsed.
TargetField string `config:"target_field"` // Target field for the parsed time value. The target value is always written as UTC. Defaults to @timestamp.
Layouts []string `config:"layouts" validate:"required"` // Timestamp layouts that define the expected time value format.
Timezone *cfgtype.Timezone `config:"timezone"` // IANA time zone (e.g. America/New_York) or fixed offset to use when parsing a timestamp not containing a timezone.
IgnoreMissing bool `config:"ignore_missing"` // Ignore errors when the source field is missing.
IgnoreFailure bool `config:"ignore_failure"` // Ignore errors when parsing the timestamp.
TestTimestamps []string `config:"test"` // A list of timestamps that must parse successfully when loading the processor.
ID string `config:"id"` // An identifier for this processor. Useful for debugging.
}

func defaultConfig() config {
Expand Down
2 changes: 1 addition & 1 deletion libbeat/processors/timestamp/docs/timestamp.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ If a layout does not contain a year then the current year in the specified
| `field` | yes | | Source field containing the time to be parsed. |
| `target_field` | no | @timestamp | Target field for the parsed time value. The target value is always written as UTC. |
| `layouts` | yes | | Timestamp layouts that define the expected time value format. In addition layouts, `UNIX` and `UNIX_MS` are accepted. |
| `timezone` | no | UTC | Time zone (e.g. America/New_York) to use when parsing a timestamp not containing a time zone. |
| `timezone` | no | UTC | IANA time zone name (e.g. `America/New_York`) or fixed time offset (e.g. `+0200`) to use when parsing times that do not contain a time zone. `Local` may be specified to use the machine's local time zone.|
| `ignore_missing` | no | false | Ignore errors when the source field is missing. |
| `ignore_failure` | no | false | Ignore all errors produced by the processor. |
| `test` | no | | A list of timestamps that must parse successfully when loading the processor. |
Expand Down
23 changes: 1 addition & 22 deletions libbeat/processors/timestamp/timestamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"fmt"
"time"

"4d63.com/tz"
"github.com/pkg/errors"

"github.com/elastic/beats/v7/libbeat/beat"
Expand Down Expand Up @@ -57,16 +56,11 @@ func New(cfg *common.Config) (processors.Processor, error) {
}

func newFromConfig(c config) (*processor, error) {
loc, err := loadLocation(c.Timezone)
if err != nil {
return nil, errors.Wrap(err, "failed to load timezone")
}

p := &processor{
config: c,
log: logp.NewLogger(logName),
isDebug: logp.IsDebug(logName),
tz: loc,
tz: c.Timezone.Location(),
}
if c.ID != "" {
p.log = p.log.With("instance_id", c.ID)
Expand All @@ -84,21 +78,6 @@ func newFromConfig(c config) (*processor, error) {
return p, nil
}

var timezoneFormats = []string{"-07", "-0700", "-07:00"}

func loadLocation(timezone string) (*time.Location, error) {
for _, format := range timezoneFormats {
t, err := time.Parse(format, timezone)
if err == nil {
name, offset := t.Zone()
return time.FixedZone(name, offset), nil
}
}

// Rest of location formats
return tz.LoadLocation(timezone)
}

func (p *processor) String() string {
return fmt.Sprintf("timestamp=[field=%s, target_field=%v, timezone=%v, layouts=%v]",
p.Field, p.TargetField, p.tz, p.Layouts)
Expand Down
Loading

0 comments on commit c47f3c9

Please sign in to comment.