#############################################################################
# Copyright (c) 2017 Balabit
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# As an additional exemption you are allowed to compile & link against the
# OpenSSL libraries as published by the OpenSSL project. See the file
# COPYING for details.
#
#############################################################################

#
# logging timestamps
# logging timezone
# logging sequence-id
# logging origin-id
# logging fraction of a second
#
#
# <pri>(sequence: )?(origin: )?(timestamp? timezone?: )?%msg
#
# Alternatively, we see Cisco NGFW firewall logs with ISO 8601 timestamp and with the following format:
# <pri>(timestamp)(timezone) (origin) : %msg

#<189>29: foo: *Apr 29 13:58:40.411: %SYS-5-CONFIG_I: Configured from console by console
#<190>30: foo: *Apr 29 13:58:46.411: %SYS-6-LOGGINGHOST_STARTSTOP: Logging to host 192.168.1.239 stopped - CLI initiated
#<190>31: foo: *Apr 29 13:58:46.411: %SYS-6-LOGGINGHOST_STARTSTOP: Logging to host 192.168.1.239 started - CLI initiated<189>32: 0.0.0.0: *Apr 29 13:59:12.491: %SYS-5-CONFIG_I: Configured from console by console<189>33: 0.0.0.0: *Apr 29 13:59:26.415: %SYS-5-CONFIG_I: Configured from console by console<189>34: 0.0.0.0: *Apr 29 13:59:56.603: %SYS-5-CONFIG_I: Configured from console by console^[[<189>35: *Apr 29 14:00:16.059: %SYS-5-CONFIG_I: Configured from console by console
#<190>32: foo: *Apr 29 13:58:46.411: %SYSMGR-STANDBY-3-SHUTDOWN_START: The System Manager has started the shutdown procedure.
# A leading dot marks an out-of-sync timestamp
#<180>782431: machine1: .Nov 18 21:03:22.631 GMT: %CDP-4-NATIVE_VLAN_MISMATCH: Native VLAN mismatch discovered on TenGigabitEthernet.
#<166>2022-02-16T15:31:53Z na-zy-int-fp1140-p02 : %FTD-6-305012: Teardown dynamic TCP translation from FOO-WAN_IN:10.44.60.80/59877 to FOO-OUTSIDE:6.7.8.9/59877 duration 0:01:01

@define cisco-parser-timestamp-pattern '^[\*\.]?([A-Za-z]{3} [0-9 ]\d (\d{4} )?\d{2}:\d{2}:\d{2}(\.\d{3})?( (AM|PM))?)'
@define cisco-parser-ISO-timestamp-pattern '^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})'

#
# parses a cisco timestamp with explicit date-parser
# It ignores timezone information
#
block parser cisco-timestamp-parser(template()) {
    channel {
        parser {
            regexp-parser(patterns('`cisco-parser-timestamp-pattern`' '`cisco-parser-ISO-timestamp-pattern`') template(`template`));
        };
        parser {
            date-parser(format('%b %d %I:%M:%S %p.%f',
                               '%b %d %I:%M:%S %p',
                               '%b %d %H:%M:%S.%f',
                               '%b %d %H:%M:%S',
                               '%b %d %Y %H:%M:%S.%f',
                               '%b %d %Y %H:%M:%S',
                               '%Y-%m-%dT%H:%M:%S')
                        template("$1"));
        };
    };
};

block parser cisco-triplet-parser(template() prefix()) {
    channel {
        if {
            parser {
                csv-parser(delimiters(chars('-')) template(`template`)
                           columns('`prefix`facility', '`prefix`severity', '`prefix`mnemonic')
			   drop-invalid(yes));
            };
        } else {
	    parser {
                csv-parser(delimiters(chars('-')) template(`template`)
                           columns('`prefix`facility', '4', '`prefix`severity', '`prefix`mnemonic')
                           drop-invalid(yes));
            };
            rewrite { set("${`prefix`facility}-$4" value('`prefix`facility')); };
        };
    };
};

block parser cisco-parser(prefix(".cisco.") template("$MSG")) {
    channel {
        parser {
	    # parse syslog <pri> field
            syslog-parser(flags(no-header) template(`template`));

            # split msg and header right before the '%', Cisco messages may
            # have a variable number of ': ' terminated values
            csv-parser(delimiters(chars('') strings(': %'))
                       columns('1', '2', '3') flags(greedy) drop-invalid(yes));

            csv-parser(delimiters(chars(':')) template("$2") columns('3'));
            cisco-triplet-parser(template("$3") prefix(`prefix`));
        };
        rewrite {
            set('%$2', value("MSG"));

            # drop "seqno: " if present
            subst("^([0-9]+: )?", "", value('1'));

        };

        if {
            if {
              parser { regexp-parser(patterns('`cisco-parser-ISO-timestamp-pattern`\w+ (?<HOST>\S+)\s*$') template('$1')); };
            };
            parser { cisco-timestamp-parser(template("$1")); };
        } elif {
            parser { regexp-parser(patterns("^(?'HOST'[^:]+): (.*)") template('$1')); };
            parser { cisco-timestamp-parser(template("$2")); };
        } elif {
            parser { regexp-parser(patterns("^(?'HOST'[^:]+)$") template('$1')); };
        } else {
            parser { regexp-parser(patterns("^$") template('$1')); };
        };
    };
};

application cisco[syslog-raw] {
	filter { message(": %" type(string) flags(substring)); };
	parser { cisco-parser(); };
};
