]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
modbus: add eve logging
authorSimon Dugas <simon.dugas@cyber.gc.ca>
Fri, 19 Feb 2021 21:43:55 +0000 (16:43 -0500)
committerVictor Julien <victor@inliniac.net>
Tue, 4 May 2021 08:43:10 +0000 (10:43 +0200)
rust/src/modbus/log.rs [new file with mode: 0644]
rust/src/modbus/mod.rs
src/Makefile.am
src/output-json-alert.c
src/output-json-modbus.c [new file with mode: 0644]
src/output-json-modbus.h [new file with mode: 0644]
src/output.c
src/suricata-common.h
src/util-profiling.c

diff --git a/rust/src/modbus/log.rs b/rust/src/modbus/log.rs
new file mode 100644 (file)
index 0000000..ff8eef2
--- /dev/null
@@ -0,0 +1,148 @@
+/* Copyright (C) 2021 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+use super::modbus::ModbusTransaction;
+use crate::jsonbuilder::{JsonBuilder, JsonError};
+
+use sawp_modbus::{Data, Message, Read, Write};
+
+#[no_mangle]
+pub extern "C" fn rs_modbus_to_json(tx: &mut ModbusTransaction, js: &mut JsonBuilder) -> bool {
+    log(tx, js).is_ok()
+}
+
+/// populate a json object with transactional information, for logging
+fn log(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> {
+    js.open_object("modbus")?;
+    js.set_uint("id", tx.id)?;
+
+    if let Some(req) = &tx.request {
+        js.open_object("request")?;
+        log_message(&req, js)?;
+        js.close()?;
+    }
+
+    if let Some(resp) = &tx.response {
+        js.open_object("response")?;
+        log_message(&resp, js)?;
+        js.close()?;
+    }
+
+    js.close()?;
+    Ok(())
+}
+
+fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
+    js.set_uint("transaction_id", msg.transaction_id.into())?;
+    js.set_uint("protocol_id", msg.protocol_id.into())?;
+    js.set_uint("unit_id", msg.unit_id.into())?;
+    js.set_uint("function_raw", msg.function.raw.into())?;
+    js.set_string("function_code", &msg.function.code.to_string())?;
+    js.set_string("access_type", &msg.access_type.to_string())?;
+    js.set_string("category", &msg.category.to_string())?;
+    js.set_string("error_flags", &msg.error_flags.to_string())?;
+
+    match &msg.data {
+        Data::Exception(exc) => {
+            js.open_object("exception")?;
+            js.set_uint("raw", exc.raw.into())?;
+            js.set_string("code", &exc.code.to_string())?;
+            js.close()?;
+        }
+        Data::Diagnostic { func, data } => {
+            js.open_object("diagnostic")?;
+            js.set_uint("raw", func.raw.into())?;
+            js.set_string("code", &func.code.to_string())?;
+            js.set_string_from_bytes("data", &data)?;
+            js.close()?;
+        }
+        Data::MEI { mei_type, data } => {
+            js.open_object("mei")?;
+            js.set_uint("raw", mei_type.raw.into())?;
+            js.set_string("code", &mei_type.code.to_string())?;
+            js.set_string_from_bytes("data", &data)?;
+            js.close()?;
+        }
+        Data::Read(read) => {
+            js.open_object("read")?;
+            log_read(read, js)?;
+            js.close()?;
+        }
+        Data::Write(write) => {
+            js.open_object("write")?;
+            log_write(write, js)?;
+            js.close()?;
+        }
+        Data::ReadWrite { read, write } => {
+            js.open_object("read")?;
+            log_read(read, js)?;
+            js.close()?;
+            js.open_object("write")?;
+            log_write(write, js)?;
+            js.close()?;
+        }
+        Data::ByteVec(data) => {
+            js.set_string_from_bytes("data", &data)?;
+        }
+        Data::Empty => {}
+    }
+
+    Ok(())
+}
+
+fn log_read(read: &Read, js: &mut JsonBuilder) -> Result<(), JsonError> {
+    match read {
+        Read::Request { address, quantity } => {
+            js.set_uint("address", (*address).into())?;
+            js.set_uint("quantity", (*quantity).into())?;
+        }
+        Read::Response(data) => {
+            js.set_string_from_bytes("data", &data)?;
+        }
+    }
+
+    Ok(())
+}
+
+fn log_write(write: &Write, js: &mut JsonBuilder) -> Result<(), JsonError> {
+    match write {
+        Write::MultReq {
+            address,
+            quantity,
+            data,
+        } => {
+            js.set_uint("address", (*address).into())?;
+            js.set_uint("quantity", (*quantity).into())?;
+            js.set_string_from_bytes("data", &data)?;
+        }
+        Write::Mask {
+            address,
+            and_mask,
+            or_mask,
+        } => {
+            js.set_uint("address", (*address).into())?;
+            js.set_uint("and_mask", (*and_mask).into())?;
+            js.set_uint("or_mask", (*or_mask).into())?;
+        }
+        Write::Other { address, data } => {
+            js.set_uint("address", (*address).into())?;
+            js.set_uint("data", (*data).into())?;
+        }
+    }
+
+    Ok(())
+}
index 58b9951fe6de3fb06054f9077f9b413710e8b3e7..50e65939047f74434e6ea30359c0326504cc89ca 100644 (file)
@@ -16,4 +16,5 @@
  */
 
 pub mod detect;
+pub mod log;
 pub mod modbus;
index 246249f5558dd2219ebabac28b3b54bb18644561..151b2f7c3738417811f0c53b6d23f917578ea8e7 100755 (executable)
@@ -397,6 +397,7 @@ noinst_HEADERS = \
        output-json-ike.h \
        output-json-krb5.h \
        output-json-metadata.h \
+       output-json-modbus.h \
        output-json-mqtt.h \
        output-json-netflow.h \
        output-json-nfs.h \
@@ -973,6 +974,7 @@ libsuricata_c_a_SOURCES = \
        output-json-ike.c \
        output-json-krb5.c \
        output-json-metadata.c \
+       output-json-modbus.c \
        output-json-mqtt.c \
        output-json-netflow.c \
        output-json-nfs.c \
index 81d71631d34bfba99c23cf65fbc69f1ac18c8831..ebb3e911e3cad242a8b80eef5d781691527ba550 100644 (file)
@@ -72,6 +72,7 @@
 #include "output-json-rfb.h"
 #include "output-json-mqtt.h"
 #include "output-json-ike.h"
+#include "output-json-modbus.h"
 
 #include "util-byte.h"
 #include "util-privs.h"
@@ -547,6 +548,12 @@ static void AlertAddAppLayer(const Packet *p, JsonBuilder *jb,
         case ALPROTO_RDP:
             AlertJsonRDP(p->flow, tx_id, jb);
             break;
+        case ALPROTO_MODBUS:
+            jb_get_mark(jb, &mark);
+            if (!JsonModbusAddMetadata(p->flow, tx_id, jb)) {
+                jb_restore_mark(jb, &mark);
+            }
+            break;
         default:
             break;
     }
diff --git a/src/output-json-modbus.c b/src/output-json-modbus.c
new file mode 100644 (file)
index 0000000..1918f02
--- /dev/null
@@ -0,0 +1,160 @@
+/* Copyright (C) 2019-2020 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "suricata-common.h"
+#include "debug.h"
+#include "detect.h"
+#include "pkt-var.h"
+#include "conf.h"
+#include "threads.h"
+#include "threadvars.h"
+#include "tm-threads.h"
+#include "util-unittest.h"
+#include "util-buffer.h"
+#include "util-debug.h"
+#include "util-byte.h"
+#include "output.h"
+#include "output-json.h"
+#include "app-layer.h"
+#include "app-layer-parser.h"
+#include "output-json-modbus.h"
+#include "rust.h"
+
+typedef struct LogModbusFileCtx_ {
+    LogFileCtx *file_ctx;
+    OutputJsonCtx *eve_ctx;
+} LogModbusFileCtx;
+
+typedef struct JsonModbusLogThread_ {
+    LogModbusFileCtx *modbuslog_ctx;
+    OutputJsonThreadCtx *ctx;
+} JsonModbusLogThread;
+
+static int JsonModbusLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f,
+        void *state, void *tx, uint64_t tx_id)
+{
+    JsonModbusLogThread *thread = thread_data;
+
+    JsonBuilder *js =
+            CreateEveHeader(p, LOG_DIR_FLOW, "modbus", NULL, thread->modbuslog_ctx->eve_ctx);
+    if (unlikely(js == NULL)) {
+        return TM_ECODE_OK;
+    }
+    if (!rs_modbus_to_json(tx, js)) {
+        jb_free(js);
+        return TM_ECODE_FAILED;
+    }
+    OutputJsonBuilderBuffer(js, thread->ctx);
+
+    jb_free(js);
+    return TM_ECODE_OK;
+}
+
+static void OutputModbusLogDeInitCtxSub(OutputCtx *output_ctx)
+{
+    LogModbusFileCtx *modbuslog_ctx = (LogModbusFileCtx *)output_ctx->data;
+    SCFree(modbuslog_ctx);
+    SCFree(output_ctx);
+}
+
+static OutputInitResult OutputModbusLogInitSub(ConfNode *conf, OutputCtx *parent_ctx)
+{
+    OutputInitResult result = { NULL, false };
+    OutputJsonCtx *ajt = parent_ctx->data;
+
+    LogModbusFileCtx *modbuslog_ctx = SCCalloc(1, sizeof(*modbuslog_ctx));
+    if (unlikely(modbuslog_ctx == NULL)) {
+        return result;
+    }
+    modbuslog_ctx->file_ctx = ajt->file_ctx;
+    modbuslog_ctx->eve_ctx = ajt;
+
+    OutputCtx *output_ctx = SCCalloc(1, sizeof(*output_ctx));
+    if (unlikely(output_ctx == NULL)) {
+        SCFree(modbuslog_ctx);
+        return result;
+    }
+    output_ctx->data = modbuslog_ctx;
+    output_ctx->DeInit = OutputModbusLogDeInitCtxSub;
+
+    AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_MODBUS);
+
+    SCLogDebug("modbus log sub-module initialized.");
+
+    result.ctx = output_ctx;
+    result.ok = true;
+    return result;
+}
+
+static TmEcode JsonModbusLogThreadInit(ThreadVars *t, const void *initdata, void **data)
+{
+    if (initdata == NULL) {
+        SCLogDebug("Error getting context for EveLogModbus. \"initdata\" is NULL.");
+        return TM_ECODE_FAILED;
+    }
+
+    JsonModbusLogThread *thread = SCCalloc(1, sizeof(*thread));
+    if (unlikely(thread == NULL)) {
+        return TM_ECODE_FAILED;
+    }
+
+    thread->modbuslog_ctx = ((OutputCtx *)initdata)->data;
+    thread->ctx = CreateEveThreadCtx(t, thread->modbuslog_ctx->eve_ctx);
+    if (thread->ctx == NULL) {
+        goto error_exit;
+    }
+
+    *data = (void *)thread;
+    return TM_ECODE_OK;
+
+error_exit:
+    SCFree(thread);
+    return TM_ECODE_FAILED;
+}
+
+static TmEcode JsonModbusLogThreadDeinit(ThreadVars *t, void *data)
+{
+    JsonModbusLogThread *thread = (JsonModbusLogThread *)data;
+    if (thread == NULL) {
+        return TM_ECODE_OK;
+    }
+    SCFree(thread);
+    return TM_ECODE_OK;
+}
+
+bool JsonModbusAddMetadata(const Flow *f, uint64_t tx_id, JsonBuilder *js)
+{
+    void *state = FlowGetAppState(f);
+    if (state) {
+        void *tx = AppLayerParserGetTx(f->proto, ALPROTO_MODBUS, state, tx_id);
+        if (tx) {
+            return rs_modbus_to_json(tx, js);
+        }
+    }
+
+    return false;
+}
+
+void JsonModbusLogRegister(void)
+{
+    /* Register as an eve sub-module. */
+    OutputRegisterTxSubModule(LOGGER_JSON_MODBUS, "eve-log", "JsonModbusLog", "eve-log.modbus",
+            OutputModbusLogInitSub, ALPROTO_MODBUS, JsonModbusLogger, JsonModbusLogThreadInit,
+            JsonModbusLogThreadDeinit, NULL);
+
+    SCLogDebug("modbus json logger registered.");
+}
diff --git a/src/output-json-modbus.h b/src/output-json-modbus.h
new file mode 100644 (file)
index 0000000..9bde2da
--- /dev/null
@@ -0,0 +1,24 @@
+/* Copyright (C) 2019 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef __OUTPUT_JSON_MODBUS_H__
+#define __OUTPUT_JSON_MODBUS_H__
+
+void JsonModbusLogRegister(void);
+bool JsonModbusAddMetadata(const Flow *f, uint64_t tx_id, JsonBuilder *js);
+
+#endif /* __OUTPUT_JSON_MODBUS_H__ */
index a58ac7ab74fdb76272ba38f568ed74c5fed3f6d6..66e3090a1fe15f7aa792bb11f84b87ae9b1c9301 100644 (file)
@@ -54,6 +54,7 @@
 #include "log-httplog.h"
 #include "output-json-http.h"
 #include "output-json-dns.h"
+#include "output-json-modbus.h"
 #include "log-tlslog.h"
 #include "log-tlsstore.h"
 #include "output-json-tls.h"
@@ -1071,6 +1072,8 @@ void OutputRegisterLoggers(void)
     OutputFilestoreRegister();
     /* dns */
     JsonDnsLogRegister();
+    /* modbus */
+    JsonModbusLogRegister();
     /* tcp streaming data */
     LogTcpDataLogRegister();
     /* log stats */
index 989fee41101d5114c5e26a24f4483a1301e2c46c..06947c13ee5aad6ea217de415a8bcfa076178ace 100644 (file)
@@ -453,6 +453,7 @@ typedef enum {
     LOGGER_JSON_SMB,
     LOGGER_JSON_IKE,
     LOGGER_JSON_KRB5,
+    LOGGER_JSON_MODBUS,
     LOGGER_JSON_DHCP,
     LOGGER_JSON_SNMP,
     LOGGER_JSON_SIP,
index 8ea5e7d3c1754f0634c83e4a28739a5e8ee4d29d..524a5f4ef3eac69e29742f5ba72359d5948ec4cc 100644 (file)
@@ -1305,6 +1305,7 @@ const char * PacketProfileLoggertIdToString(LoggerId id)
         CASE_CODE (LOGGER_JSON_DHCP);
         CASE_CODE (LOGGER_JSON_KRB5);
         CASE_CODE(LOGGER_JSON_IKE);
+        CASE_CODE(LOGGER_JSON_MODBUS);
         CASE_CODE (LOGGER_JSON_FTP);
         CASE_CODE (LOGGER_JSON_TFTP);
         CASE_CODE (LOGGER_JSON_SMTP);