* All .cc files should include config.h with the standard block shown below
immediately following the initial comment blocks and before anything else.
This presents a consistent view of all included header files as well as
- access to any other configure-time definitions. No .h files should include
- config.h unless they are guaranteed to be local header files (never
- installed).
+ access to any other configure-time definitions. To avoid issues, no .h files
+ should include config.h, even if not installed.
#ifdef HAVE_CONFIG_H
#include "config.h"
bool ReactModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("page") )
- return getpage(v.get_string());
-
- return true;
+ assert(v.is("page"));
+ return getpage(v.get_string());
}
std::string ReactModule::get_data()
flags |= unr[v.get_uint8()];
}
- else
- return false;
-
return true;
}
v.get_bits(ports);
config->set_geneve_ports(ports);
}
- else
- return false;
return true;
}
config->text_format = ( v.get_uint8() == 1 );
else if ( v.is("direction") )
+ {
switch ( v.get_uint8() )
{
case 0:
- {
config->direction = Connector::CONN_RECEIVE;
break;
- }
case 1:
- {
config->direction = Connector::CONN_TRANSMIT;
break;
- }
case 2:
- {
config->direction = Connector::CONN_DUPLEX;
break;
- }
default:
return false;
}
-
- else
- return false;
-
+ }
return true;
}
config->base_port = v.get_uint16();
else if ( v.is("setup") )
+ {
switch ( v.get_uint8() )
{
case 0:
- {
config->setup = TcpConnectorConfig::CALL;
break;
- }
case 1:
- {
config->setup = TcpConnectorConfig::ANSWER;
break;
- }
default:
return false;
}
-
- else
- return false;
-
+ }
return true;
}
// file_oleheader.cc author Amarnath Nayak amarnaya@cisco.com
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "file_oleheader.h"
unsigned char hdr_sig[8] = { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 };
//--------------------------------------------------------------------------
// text_config_output.cc author Serhii Vlasiuk <svlasiuk@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "text_config_output.h"
#include <iomanip>
else if ( v.is("log_sys_time") )
config.log_sys_time = v.get_bool();
- else
- return false;
-
return true;
}
return false;
}
}
- else
- return false;
-
return true;
}
{
convert_milliseconds_to_timeval(v.get_uint32(), &config->min_sync_interval);
}
- else
- return false;
return true;
}
virtual void set_extra_data(snort::Packet*, uint32_t /*flag*/) { }
virtual bool is_sequenced(uint8_t /*dir*/) { return true; }
- virtual bool are_packets_missing(uint8_t /*dir*/) { return true; }
+ virtual bool are_packets_missing(uint8_t /*dir*/) { return false; }
virtual bool are_client_segments_queued() { return false; }
virtual void disable_reassembly(snort::Flow*) { }
-
+//--------------------------------------------------------------------------
// Copyright (C) 2019-2021 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
-
+//--------------------------------------------------------------------------
// Copyright (C) 2019-2021 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// flow_stash_test.cc author Shravan Rangaraju <shrarang@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include <string>
#include "flow/flow_stash.h"
ssn->set_extra_data(nullptr, 1);
CHECK(true == ssn->is_sequenced(1));
- CHECK(true == ssn->are_packets_missing(1));
-
+ CHECK(false == ssn->are_packets_missing(1));
CHECK(SSN_DIR_NONE == ssn->get_reassembly_direction());
CHECK(SSN_MISSING_NONE == ssn->missing_in_reassembled(1));
// host_cache_allocator.cc author Silviu Minut <sminut@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#ifndef HOST_CACHE_ALLOCATOR_CC
#define HOST_CACHE_ALLOCATOR_CC
}
else if ( v.is("memcap") )
memcap = v.get_size();
- else
- return false;
return true;
}
else if ( v.is("port") )
host_cache[addr]->update_service_port(app, v.get_uint16());
+
else if ( v.is("proto") )
{
const IpProtocol mask[] =
host_cache[addr]->update_service_proto(app, mask[v.get_uint8()]);
}
- else
- return false;
-
return true;
}
SOURCES
../host_cache.cc
../host_tracker.cc
- ../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../network_inspectors/rna/test/rna_flow_stubs.cc
../../sfip/sf_ip.cc
)
../../framework/module.cc
../../framework/value.cc
../../hash/lru_cache_shared.cc
- ../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../network_inspectors/rna/test/rna_flow_stubs.cc
../../sfip/sf_ip.cc
$<TARGET_OBJECTS:catch_tests>
LIBS
add_cpputest( host_tracker_test
SOURCES
../host_tracker.cc
- ../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../network_inspectors/rna/test/rna_flow_stubs.cc
../../sfip/sf_ip.cc
)
../../framework/module.cc
../../framework/parameter.cc
../../framework/value.cc
- ../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../network_inspectors/rna/test/rna_flow_stubs.cc
../../sfip/sf_ip.cc
$<TARGET_OBJECTS:catch_tests>
LIBS
add_cpputest( host_cache_allocator_ht_test
SOURCES
../host_tracker.cc
- ../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../network_inspectors/rna/test/rna_flow_stubs.cc
../../sfip/sf_ip.cc
)
add_cpputest( host_cache_allocator_test
SOURCES
../host_tracker.cc
- ../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../network_inspectors/rna/test/rna_flow_stubs.cc
)
bool AckModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
data.offset_type = REL_OFFSET;
data.offset = v.get_int32();
}
- else
- return false;
-
return true;
}
else if ( v.is("relative") )
data.flags |= BASE64DECODE_RELATIVE_FLAG;
- else
- return false;
-
return true;
}
bool BerDataModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("~type") )
- type = v.get_uint32();
- else
- return false;
-
+ assert(v.is("~type"));
+ type = v.get_uint32();
return true;
}
else if ( v.is("optional") )
optional = true;
- else
- return false;
-
return true;
}
if ( v.is("relative") )
relative = true;
- else
- return false;
-
return true;
}
else if (v.is("bitmask"))
data.bitmask_val = v.get_uint32();
- else
- return false;
-
return true;
}
CHECK(obj.set(nullptr, v, nullptr));
CHECK_THAT(obj.data, ByteExtractDataEquals(expected));
}
- SECTION("invalid set")
- {
- Value v(1023.0);
- Parameter p{
- "error", Parameter::PT_INT, "nan", nullptr,
- "not an option"};
- v.set(&p);
- ByteExtractData expected;
- INITIALIZE(expected, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, nullptr);
-
- CHECK(!obj.set(nullptr, v, nullptr));
- CHECK_THAT(obj.data, ByteExtractDataEquals(expected));
- }
-
delete[] obj.data.name;
}
else if (v.is("bitmask"))
data.bitmask_val = v.get_uint32();
- else
- return false;
-
return true;
}
{
Value value(false);
- SECTION("All params incorrect")
- {
- REQUIRE(module_jump.set(nullptr, value, nullptr) == false);
- }
-
SECTION("Case param \"~count\"")
{
Parameter param("~count", snort::Parameter::Type::PT_BOOL,
else if (v.is("result"))
data.result_name = snort_strdup(v.get_string());
- else
- return false;
-
return true;
}
ByteMathModule obj;
obj.begin(nullptr, 0, nullptr);
- SECTION("invalid parameter")
- {
- Value v(1023.0);
- Parameter p{"error", Parameter::PT_INT, "nan", nullptr,
- "not an option"};
- v.set(&p);
- ByteMathData expected;
- INITIALIZE(expected, 0, 0, 0, 0, 0, BM_PLUS, 0, 0, 0, 0, 0, 0, 0);
-
- CHECK(!obj.set(nullptr, v, nullptr));
- CHECK_THAT(obj.data, ByteMathDataEquals(expected));
- }
SECTION("rvalue = 0")
{
Value v("0");
else if (v.is("bitmask"))
data.bitmask_val = v.get_uint32();
- else
- return false;
-
return true;
}
{
Value value(false);
- SECTION("All params incorrect")
- {
- REQUIRE(module_test.set(nullptr, value, nullptr) == false);
- }
-
SECTION("Case param \"~count\"")
{
Parameter param("~count", snort::Parameter::Type::PT_BOOL,
bool ClassTypeModule::set(const char*, Value& v, SnortConfig* sc)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
type = get_classification(sc, v.get_string());
if ( !type and sc->dump_rule_info() )
cd->pmd.fp_length = v.get_uint16();
cd->pmd.set_fast_pattern();
}
- else
- return false;
-
return true;
}
#define CVS_COMMAND_DELIMITER '\n'
#define CVS_COMMAND_SEPARATOR ' '
-#define CVS_CONF_INVALID_ENTRY_STR "invalid-entry"
-
#define CVS_NO_ALERT 0
#define CVS_ALERT 1
CVS_END_OF_ENUM
} CvsTypes;
-typedef struct _CvsRuleOption
+struct CvsRuleOption
{
- CvsTypes type;
-} CvsRuleOption;
+ CvsTypes type = CVS_INVALID_ENTRY;
+};
/* represents a CVS command with argument */
typedef struct _CvsCommand
static const Parameter s_params[] =
{
- { CVS_CONF_INVALID_ENTRY_STR, Parameter::PT_IMPLIED, nullptr, nullptr,
+ { "invalid-entry", Parameter::PT_IMPLIED, nullptr, nullptr,
"looks for an invalid Entry string" },
{ nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr }
public:
CvsModule() : Module(s_name, s_help, s_params) { }
- bool begin(const char*, int, SnortConfig*) override;
- bool set(const char*, Value&, SnortConfig*) override;
-
ProfileStats* get_profile() const override
{ return &cvsPerfStats; }
{ return DETECT; }
public:
- CvsRuleOption data = {};
+ CvsRuleOption data;
};
-bool CvsModule::begin(const char*, int, SnortConfig*)
-{
- memset(&data, 0, sizeof(data));
- return true;
-}
-
-bool CvsModule::set(const char*, Value& v, SnortConfig*)
-{
- if ( !v.is(CVS_CONF_INVALID_ENTRY_STR) )
- return false;
-
- data.type = CVS_INVALID_ENTRY;
- return true;
-}
-
//-------------------------------------------------------------------------
// api methods
//-------------------------------------------------------------------------
else if ( v.is("seconds") )
thdx.seconds = v.get_uint32();
- else
- return false;
-
return true;
}
bool DsizeModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool EnableModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~enable") )
- return false;
-
+ assert(v.is("~enable"));
enable = IpsPolicy::Enable(v.get_uint8());
return true;
}
bool FileTypeModule::set(const char*, Value& v, SnortConfig* sc)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
v.set_first_token();
std::string tok;
else if ( v.is("~mask_flags") )
flags_parse_mask(v.get_string(), &data);
- else
- return false;
-
return true;
}
else if ( v.is("only_frag") )
data.only_reassembled |= ONLY_FRAG;
- else
- return false;
-
return true;
}
else if ( v.is("~bits") )
bits = v.get_string();
- else
- return false;
-
return true;
}
// which is the string of command line arguments
bool FragBitsModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("~flags") )
- fragBitsData.parse_fragbits(v.get_string());
- else
- return false;
-
+ assert(v.is("~flags"));
+ fragBitsData.parse_fragbits(v.get_string());
return true;
}
bool FragOffsetModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool GidModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
gid = v.get_uint32();
return true;
}
else if ( v.is("length") )
hmd->length = v.get_uint16();
- else
- return false;
-
return true;
}
bool IcmpIdModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool IcmpSeqModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool IcodeModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool IpIdModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool IpProtoModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("~proto") )
- ip_proto_parse(v.get_string(), &data);
-
- else
- return false;
-
+ assert(v.is("~proto"));
+ ip_proto_parse(v.get_string(), &data);
return true;
}
bool IpOptModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("~opt") )
- ipopts_parse(v.get_string(), &data);
-
- else
- return false;
-
+ assert(v.is("~opt"));
+ ipopts_parse(v.get_string(), &data);
return true;
}
else if ( v.is("relative") )
data.flags |= ISDATAAT_RELATIVE_FLAG;
- else
- return false;
-
return true;
}
bool ItypeModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool MetadataModule::set(const char*, Value& v, SnortConfig* sc)
{
- if ( !v.is("*") )
- return false;
+ assert(v.is("*"));
if ( !match and !sc->metadata_filter.empty() )
match = strstr(v.get_string(), sc->metadata_filter.c_str()) != nullptr;
bool MsgModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
msg = v.get_string();
return true;
}
bool PcreModule::set(const char* name, Value& v, SnortConfig* sc)
{
- if ( v.is("~re") )
- {
- re = v.get_string();
+ assert(v.is("~re"));
+ re = v.get_string();
- if( mod_regex )
- mod_regex = mod_regex->set(name, v, sc) ? mod_regex : nullptr;
- }
- else
- return false;
+ if( mod_regex )
+ mod_regex = mod_regex->set(name, v, sc) ? mod_regex : nullptr;
return true;
}
bool PriorityModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
priority = v.get_int32();
return true;
}
bool ReferenceModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~ref") )
- return false;
+ assert(v.is("~ref"));
const char* ref = v.get_string();
const char* sep = strchr(ref, ',');
else if ( v.is("fast_pattern") )
config.pmd.set_fast_pattern();
-
else if ( v.is("nocase") )
{
config.pmd.mpse_flags |= HS_FLAG_CASELESS;
config.pmd.set_no_case();
}
- else
- return false;
-
return true;
}
{
public:
RemModule() : Module(s_name, s_help, s_params) { }
- bool set(const char*, Value&, SnortConfig*) override;
Usage get_usage() const override
{ return DETECT; }
};
-bool RemModule::set(const char*, Value& v, SnortConfig*)
-{
- if ( !v.is("~") )
- return false;
-
- return true;
-}
-
//-------------------------------------------------------------------------
// api methods
//-------------------------------------------------------------------------
bool ReplModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("~") )
- replace_parse(v.get_string(), data);
-
- else
- return false;
-
+ assert(v.is("~"));
+ replace_parse(v.get_string(), data);
return true;
}
bool RevModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
rev = v.get_uint32();
return true;
}
else if ( v.is("~proc") )
return set(v, data.procedure, RPC_CHECK_PROCEDURE);
- else
- return false;
-
return true;
}
bool SdPatternModule::begin(const char*, int, SnortConfig*)
{
+ if ( hs_valid_platform() != HS_SUCCESS )
+ {
+ ParseError("This host does not support Hyperscan.");
+ return false;
+ }
+
config = SdPatternConfig();
return true;
}
}
else if ( v.is("threshold") )
config.threshold = v.get_uint32();
- else
- return false;
- // Check if built-in pattern should be used.
+ return true;
+}
+
+bool SdPatternModule::end(const char*, int, SnortConfig*)
+{
IpsPolicy* p = get_ips_policy();
+
if (config.pii == "credit_card")
{
config.pii = SD_CREDIT_PATTERN_ALL;
config.forced_boundary = true;
}
- return true;
-}
-
-bool SdPatternModule::end(const char*, int, SnortConfig*)
-{
- if ( hs_valid_platform() != HS_SUCCESS )
- {
- ParseError("This host does not support Hyperscan.");
- return false;
- }
-
hs_compile_error_t* err = nullptr;
if ( hs_compile(config.pii.c_str(), HS_FLAG_DOTALL|HS_FLAG_SOM_LEFTMOST, HS_MODE_BLOCK,
bool SeqModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool ServiceModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("*") )
- return false;
-
+ assert(v.is("*"));
std::string svc = v.get_string();
for ( const auto& p : services )
}
}
services.emplace_back(svc);
-
return true;
}
bool SidModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
sid = v.get_uint32();
return true;
}
else if ( v.is("relative") )
relative_flag = true;
- else
- return false;
-
return true;
}
bool SoidModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
soid = v.get_string();
return true;
}
tag->tag_metric |= TAG_METRIC_BYTES;
tag->tag_bytes = v.get_uint32();
}
- else
- return false;
-
return true;
}
bool TargetModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
assert(v.get_uint8() <= TARGET_MAX);
target = static_cast<Target>(v.get_uint8() + 1);
-
return true;
}
bool TosModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
bool TtlModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
-
//--------------------------------------------------------------------------
// Copyright (C) 2021 Cisco and/or its affiliates. All rights reserved.
//
//--------------------------------------------------------------------------
// ips_vba_data.cc author Amarnath Nayak <amarnaya@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "ips_vba_data.h"
#include "framework/module.h"
//--------------------------------------------------------------------------
// ips_vba_data.h author Amarnath Nayak <amarnaya@cisco.com>
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
#include "detection/detection_engine.h"
#include "framework/cursor.h"
#include "framework/ips_option.h"
bool WindowModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return data.validate(v.get_string(), RANGE);
}
CHECK(mod->set(ips_regex->name, vb, nullptr));
}
-TEST(ips_regex_module, config_fail_name)
-{
- Value vs("lazy");
- Parameter bad { "bad", Parameter::PT_STRING, nullptr, nullptr, "bad" };
- vs.set(&bad);
- CHECK(!mod->set(ips_regex->name, vs, nullptr));
- expect = 1;
- end = false;
-}
-
TEST(ips_regex_module, config_fail_regex)
{
Value vs("\"/[[:fubar:]]/\"");
set (LOGGER_SOURCES
alert_luajit.cc
- alert_sf_socket.cc
log_codecs.cc
loggers.cc
loggers.h
else if ( v.is("separator") )
sep = v.get_string();
- else
- return false;
-
return true;
}
else if ( v.is("limit") )
limit = v.get_size() * 1024 * 1024;
- else
- return false;
-
return true;
}
else if ( v.is("limit") )
limit = v.get_size() * 1024 * 1024;
- else
- return false;
-
return true;
}
else if ( v.is("separator") )
sep = v.get_string();
- else
- return false;
-
return true;
}
+++ /dev/null
-//--------------------------------------------------------------------------
-// Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
-// Copyright (C) 2003-2013 Sourcefire, Inc.
-//
-// 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. You may not use, modify or distribute
-// this program under any other version of the GNU General Public License.
-//
-// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
-//--------------------------------------------------------------------------
-
-/* We use some Linux only socket capabilities */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/socket.h>
-#include <sys/un.h>
-
-#include "detection/treenodes.h"
-#include "events/event.h"
-#include "framework/logger.h"
-#include "framework/module.h"
-#include "hash/ghash.h"
-#include "log/messages.h"
-#include "main/snort_config.h"
-#include "managers/event_manager.h"
-#include "parser/parser.h"
-#include "protocols/packet.h"
-#include "target_based/snort_protocols.h"
-#include "utils/util.h"
-#include "utils/util_cstring.h"
-
-using namespace snort;
-using namespace std;
-
-struct SfSock
-{
- int connected;
- int sock;
- struct sockaddr_un addr;
-};
-
-struct RuleId
-{
- unsigned gid;
- unsigned sid;
-};
-
-static THREAD_LOCAL SfSock context;
-
-typedef vector<RuleId> RuleVector;
-
-#define s_name "alert_sfsocket"
-
-//-------------------------------------------------------------------------
-// alert_sfsocket module
-//-------------------------------------------------------------------------
-
-static const Parameter rule_params[] =
-{
- { "gid", Parameter::PT_INT, "1:max32", "1",
- "rule generator ID" },
-
- { "sid", Parameter::PT_INT, "1:max32", "1",
- "rule signature ID" },
-
- { nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr }
-};
-
-static const Parameter s_params[] =
-{
- { "file", Parameter::PT_STRING, nullptr, nullptr,
- "name of unix socket file" },
-
- { "rules", Parameter::PT_LIST, rule_params, nullptr,
- "name of unix socket file" },
-
- { nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr }
-};
-
-#define s_help \
- "output event over socket"
-
-class SfSocketModule : public Module
-{
-public:
- SfSocketModule() : Module(s_name, s_help, s_params) { }
-
- bool set(const char*, Value&, SnortConfig*) override;
- bool begin(const char*, int, SnortConfig*) override;
- bool end(const char*, int, SnortConfig*) override;
-
- Usage get_usage() const override
- { return GLOBAL; }
-
-public:
- string file;
- RuleVector rulez;
- RuleId rule = {};
-};
-
-bool SfSocketModule::set(const char*, Value& v, SnortConfig*)
-{
- if ( v.is("file") )
- file = v.get_string();
-
- else if ( v.is("gid") )
- rule.gid = v.get_uint32();
-
- else if ( v.is("sid") )
- rule.sid = v.get_uint32();
-
- return true;
-}
-
-bool SfSocketModule::begin(const char*, int, SnortConfig*)
-{
- file.erase();
- rule.gid = rule.sid = 1;
- return true;
-}
-
-bool SfSocketModule::end(const char* fqn, int, SnortConfig*)
-{
- if ( !strcmp(fqn, "alert_sfsocket.rules") )
- rulez.emplace_back(rule);
-
- return true;
-}
-
-//-------------------------------------------------------------------------
-// socket stuff
-
-static int AlertSFSocket_Connect()
-{
- /* check sock value */
- if (context.sock == -1)
- FatalError("AlertSFSocket: Invalid socket\n");
-
- if (connect(context.sock, (sockaddr*)&context.addr, sizeof(context.addr)) == -1)
- {
- if (errno == ECONNREFUSED || errno == ENOENT)
- {
- LogMessage("WARNING: AlertSFSocket: Unable to connect to socket: "
- "%s.\n", get_error(errno));
- return 1;
- }
- else
- {
- FatalError("AlertSFSocket: Unable to connect to socket "
- "(%i): %s\n", errno, get_error(errno));
- }
- }
- return 0;
-}
-
-static void sock_init(const char* args)
-{
- if ( (context.sock = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0 )
- FatalError("Unable to create socket: %s\n", get_error(errno));
-
- std::string name;
- get_instance_file(name, args);
-
- memset(&context.addr, 0, sizeof(context.addr));
- context.addr.sun_family = AF_UNIX;
- SnortStrncpy(context.addr.sun_path, name.c_str(), sizeof(context.addr.sun_path));
-
- if (AlertSFSocket_Connect() == 0)
- context.connected = 1;
-}
-
-static void send_sar(uint8_t* data, unsigned len)
-{
- int tries = 0;
-
- do
- {
- tries++;
- /* connect as needed */
- if (!context.connected)
- {
- if (AlertSFSocket_Connect() != 0)
- break;
- context.connected = 1;
- }
-
- /* send request */
- if (send(context.sock, data, len, 0) == len)
- {
- /* success */
- return;
- }
- /* send failed */
- if (errno == ENOBUFS)
- {
- LogMessage("ERROR: AlertSFSocket: out of buffer space\n");
- break;
- }
- else if (errno == ECONNRESET)
- {
- context.connected = 0;
- LogMessage("WARNING: AlertSFSocket: connection reset, will attempt "
- "to reconnect.\n");
- }
- else if (errno == ECONNREFUSED)
- {
- LogMessage("WARNING: AlertSFSocket: connection refused, "
- "will attempt to reconnect.\n");
- context.connected = 0;
- }
- else if (errno == ENOTCONN)
- {
- LogMessage("WARNING: AlertSFSocket: not connected, "
- "will attempt to reconnect.\n");
- context.connected = 0;
- }
- else
- {
- LogMessage("ERROR: AlertSFSocket: unhandled error '%i' in send(): "
- "%s\n", errno, get_error(errno));
- context.connected = 0;
- }
- }
- while (tries <= 1);
- LogMessage("ERROR: AlertSFSocket: Alert not sent\n");
-}
-
-//-------------------------------------------------------------------------
-// sig stuff
-
-/* search for an OptTreeNode by sid in specific policy*/
-// FIXIT-L wow - OptTreeNode_Search should be encapsulated somewhere ...
-// (actually, the whole reason for doing this needs to be rethought)
-static OptTreeNode* OptTreeNode_Search(uint32_t, uint32_t sid)
-{
- GHashNode* hashNode;
-
- if (sid == 0)
- return nullptr;
-
- const SnortConfig* sc = SnortConfig::get_conf();
-
- for (hashNode = sc->otn_map->find_first();
- hashNode;
- hashNode = sc->otn_map->find_next())
- {
- OptTreeNode* otn = (OptTreeNode*)hashNode->data;
- RuleTreeNode* rtn = getRuntimeRtnFromOtn(otn);
-
- if ( rtn and is_network_protocol(rtn->snort_protocol_id) )
- {
- if (otn->sigInfo.sid == sid)
- return otn;
- }
- }
-
- return nullptr;
-}
-
-//-------------------------------------------------------------------------
-// sar stuff
-
-struct SnortActionRequest
-{
- uint32_t event_id;
- uint32_t tv_sec;
- uint32_t gid;
- uint32_t sid;
- uint32_t src_ip;
- uint32_t dest_ip;
- uint16_t sport;
- uint16_t dport;
- IpProtocol ip_proto;
-};
-
-static void load_sar(Packet* packet, const Event& event, SnortActionRequest& sar)
-{
- if ( !packet || !packet->ptrs.ip_api.is_ip() )
- return;
-
- // for now, only support ip4
- if ( !packet->ptrs.ip_api.is_ip4() )
- return;
-
- /* construct the action request */
- sar.event_id = event.get_event_id();
- sar.tv_sec = packet->pkth->ts.tv_sec;
- sar.gid = event.sig_info->gid;
- sar.sid = event.sig_info->sid;
-
- // when ip6 is supported:
- // * suggest TLV format where T == family, L is implied by
- // T (and not sent), and V is just the address octets in
- // network order
- // * if T is made the 1st octet of struct, bytes to read
- // can be determined by reading 1 byte
- // * addresses could be moved to end of struct in uint8_t[32]
- // and only 1st 8 used for ip4
- sar.src_ip = ntohl(packet->ptrs.ip_api.get_src()->get_ip4_value());
- sar.dest_ip = ntohl(packet->ptrs.ip_api.get_dst()->get_ip4_value());
- sar.ip_proto = packet->get_ip_proto_next();
-
- if (packet->is_tcp() || packet->is_udp())
- {
- sar.sport = packet->ptrs.sp;
- sar.dport = packet->ptrs.dp;
- }
- else
- {
- sar.sport = 0;
- sar.dport = 0;
- }
-}
-
-//-------------------------------------------------------------------------
-
-class SfSocketLogger : public Logger
-{
-public:
- SfSocketLogger(SfSocketModule*);
-
- void configure(RuleId&);
-
- void open() override;
- void close() override;
-
- void alert(Packet*, const char* msg, const Event&) override;
-
-private:
- string file;
-};
-
-SfSocketLogger::SfSocketLogger(SfSocketModule* m)
-{
- file = m->file;
-
- for ( auto r : m->rulez )
- configure(r);
-}
-
-void SfSocketLogger::configure(RuleId& r)
-{
- OptTreeNode* otn = OptTreeNode_Search(r.gid, r.sid);
-
- if ( !otn )
- ParseError("Unable to find OptTreeNode for %u:%u", r.gid, r.sid);
-
- else
- EventManager::add_output(&otn->outputFuncs, this);
-}
-
-void SfSocketLogger::open()
-{
- sock_init(file.c_str());
-}
-
-void SfSocketLogger::close()
-{
- ::close(context.sock);
- context.sock = -1;
-}
-
-void SfSocketLogger::alert(Packet* packet, const char*, const Event& event)
-{
- SnortActionRequest sar;
- load_sar(packet, event, sar);
- send_sar((uint8_t*)&sar, sizeof(sar));
-}
-
-//-------------------------------------------------------------------------
-
-static Module* mod_ctor()
-{ return new SfSocketModule; }
-
-static void mod_dtor(Module* m)
-{ delete m; }
-
-static Logger* sf_sock_ctor(Module* mod)
-{ return new SfSocketLogger((SfSocketModule*)mod); }
-
-static void sf_sock_dtor(Logger* p)
-{ delete p; }
-
-static LogApi sf_sock_api
-{
- {
- PT_LOGGER,
- sizeof(LogApi),
- LOGAPI_VERSION,
- 0,
- API_RESERVED,
- API_OPTIONS,
- s_name,
- s_help,
- mod_ctor,
- mod_dtor
- },
- OUTPUT_TYPE_FLAG__NONE,
- sf_sock_ctor,
- sf_sock_dtor
-};
-
-const BaseApi* alert_sf_socket[] =
-{
- &sf_sock_api.base,
- nullptr
-};
-
else if ( v.is("options") )
options = get_options(v.get_string());
- else
- return false;
-
return true;
}
if ( v.get_bool() )
flags |= ALERT_FLAG_MSG;
}
- else
- return false;
-
return true;
}
else if ( v.is("width") )
width = v.get_uint32();
- else
- return false;
-
return true;
}
bool TcpdumpModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("limit") )
- limit = v.get_size() * 1024 * 1024;
-
- else
- return false;
-
+ assert(v.is("limit"));
+ limit = v.get_size() * 1024 * 1024;
return true;
}
// to ensure PacketManager::log_protocols() is built into Snort++
extern const BaseApi* log_codecs[];
-extern const BaseApi* alert_sf_socket[];
-
#ifdef STATIC_LOGGERS
extern const BaseApi* alert_csv[];
extern const BaseApi* alert_fast[];
{
// loggers
PluginManager::load_plugins(log_codecs);
- PluginManager::load_plugins(alert_sf_socket);
#ifdef STATIC_LOGGERS
// alerters
logheader.sensor_id = 0;
logheader.linktype = u2.base_proto;
- if (event != nullptr)
- {
- logheader.event_id = htonl(event->get_event_reference());
- logheader.event_second = htonl(event->ref_time.tv_sec);
- }
- else
- {
- logheader.event_id = 0;
- logheader.event_second = 0;
- }
+ logheader.event_id = htonl(event->get_event_reference());
+ logheader.event_second = htonl(event->ref_time.tv_sec);
- if ( p and p->pkth )
- {
- logheader.packet_second = htonl((uint32_t)p->pkth->ts.tv_sec);
- logheader.packet_microsecond = htonl((uint32_t)p->pkth->ts.tv_usec);
- pkt_length = ( p->is_rebuilt() ) ? p->dsize : p->pktlen;
- logheader.packet_length = htonl(pkt_length + u2h_len);
- write_len += pkt_length + u2h_len;
- }
- else
- {
- logheader.packet_second = 0;
- logheader.packet_microsecond = 0;
- logheader.packet_length = 0;
- }
+ logheader.packet_second = htonl((uint32_t)p->pkth->ts.tv_sec);
+ logheader.packet_microsecond = htonl((uint32_t)p->pkth->ts.tv_usec);
+ pkt_length = ( p->is_rebuilt() ) ? p->dsize : p->pktlen;
+ logheader.packet_length = htonl(pkt_length + u2h_len);
+ write_len += pkt_length + u2h_len;
if ( config->limit && (u2.current + write_len) > config->limit )
Unified2RotateFile(config);
else if ( v.is("legacy_events") )
legacy_events = v.get_bool();
- else
- return false;
-
return true;
}
+if ( ENABLE_PIGLET )
+ set(PIGLET_FILES
+ lua_arg.h
+ lua_iface.h
+ lua_ref.cc
+ lua_ref.h
+ lua_table.h
+ lua_util.cc
+ lua_util.h
+ )
+endif ()
+
add_library (lua OBJECT
lua.cc
lua.h
- lua_ref.cc
- lua_ref.h
- lua_iface.h
- lua_util.cc
- lua_util.h
- lua_table.h
+ lua_script.h
lua_stack.h
- lua_arg.h
+ ${PIGLET_FILES}
)
target_include_directories(lua PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
--- /dev/null
+//--------------------------------------------------------------------------
+// Copyright (C) 2015-2021 Cisco and/or its affiliates. All rights reserved.
+//
+// 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. You may not use, modify or distribute
+// this program under any other version of the GNU General Public License.
+//
+// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//--------------------------------------------------------------------------
+// lua_script.h author Joel Cornett <jocornet@cisco.com>
+
+#ifndef LUA_SCRIPT_H
+#define LUA_SCRIPT_H
+
+#include <string>
+
+#include <lua.hpp>
+
+#define LUA_DIR_SEP '/'
+#define SCRIPT_DIR_VARNAME "SCRIPT_DIR"
+
+namespace Lua
+{
+inline void set_script_dir(
+ lua_State* L, const std::string& varname, const std::string& path)
+{
+ std::string dir = path.substr(0, path.rfind(LUA_DIR_SEP));
+ lua_pushlstring(L, dir.c_str(), dir.size());
+ lua_setglobal(L, varname.c_str());
+}
+}
+#endif
#ifndef LUA_UTIL_H
#define LUA_UTIL_H
-#include <string>
-
#include <lua.hpp>
-#define LUA_DIR_SEP '/'
-#define SCRIPT_DIR_VARNAME "SCRIPT_DIR"
-
namespace Lua
{
const char* fmt_expected_message(const char* type);
const char* fmt_range_message(unsigned min, unsigned max);
-
-inline void set_script_dir(
- lua_State* L, const std::string& varname, const std::string& path)
-{
- std::string dir = path.substr(0, path.rfind(LUA_DIR_SEP));
- lua_pushlstring(L, dir.c_str(), dir.size());
- lua_setglobal(L, varname.c_str());
-}
}
#endif
public:
EventQueueModule() : Module("event_queue", event_queue_help, event_queue_params) { }
bool set(const char*, Value&, SnortConfig*) override;
+ bool end(const char*, int, SnortConfig*) override;
Usage get_usage() const override
{ return CONTEXT; }
else if ( v.is("process_all_events") )
eq->process_all_events = v.get_bool();
- else
- return false;
+ return true;
+}
+
+bool EventQueueModule::end(const char*, int, SnortConfig* sc)
+{
+ EventQueueConfig* eq = sc->event_queue_config;
if ( eq->max_events < eq->log_events )
eq->max_events = eq->log_events;
else if ( v.is("queue_limit") )
fp->set_queue_limit(v.get_uint32());
- else
- return false;
-
return true;
}
else if ( v.is("text") )
text = v.get_string();
- else
- return false;
-
return true;
}
else if ( v.is("url") )
url = v.get_string();
- else
- return false;
-
return true;
}
else if ( v.is("tunnel_verdicts") )
sc->set_tunnel_verdicts(v.get_string());
- else
- return false;
-
return true;
}
else if ( v.is("obfuscate") )
v.update_mask(sc->output_flags, OUTPUT_FLAG__OBFUSCATE);
- else
- return false;
-
return true;
}
else if ( v.is("min_interval") )
sc->min_interval = v.get_uint8();
- else
- return false;
-
return true;
}
else if ( v.is("max_metadata_services") )
sc->max_metadata_services = v.get_uint8();
- else
- return false;
-
return true;
}
else if (v.is("max_ip_layers"))
sc->max_ip_layers = v.get_uint8();
- else
- return false;
-
return true;
}
return true;
}
- else
- return false;
-
return true;
}
//-------------------------------------------------------------------------
else if ( v.is("with") )
with = v.get_string();
- else
- return false;
-
return true;
}
else if (v.is("name"))
name = v.get_string();
- else
- return false;
-
return true;
}
else if ( v.is("ip") )
thdx.ip_address = sfip_var_from_string(v.get_string(), "suppress");
- else
- return false;
-
return true;
}
else if ( v.is("type") )
thdx.type = v.get_uint8();
- else
- return false;
-
return true;
}
v.get_string());
}
- else
- return false;
-
return true;
}
else if ( v.is("port") )
service.port = v.get_uint16();
- else
- return false;
-
return true;
}
void EventManager::add_plugin(const LogApi* api)
{
- // can't assert - alert_sf_socket operates differently
- //assert(api->flags & (OUTPUT_TYPE_FLAG__ALERT | OUTPUT_TYPE_FLAG__LOG));
+ assert(api->flags & (OUTPUT_TYPE_FLAG__ALERT | OUTPUT_TYPE_FLAG__LOG));
s_outputs.emplace_back(new Output(api));
}
#include "helpers/directory.h"
#include "log/messages.h"
#include "lua/lua.h"
-#include "lua/lua_util.h"
+#include "lua/lua_script.h"
#ifdef PIGLET
#include "piglet/piglet_manager.h"
else if ( v.is("threshold") )
sc->memory->threshold = v.get_uint8();
- else
- return false;
-
return true;
}
//--------------------------------------------------------------------------
// client_plugins_mock.h author author Sreeja Athirkandathil Narayanan <sathirka@cisco.com>
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
#define APPID_UT_ID 1492
namespace snort
{
// Stubs for messages
void ErrorMessage(const char*,...) { }
+// LCOV_EXCL_START
void WarningMessage(const char*,...) { }
void LogMessage(const char*,...) { }
void ParseWarning(WarningGroup, const char*, ...) { }
+// LCOV_EXCL_STOP
// Stubs for appid sessions
FlowData::FlowData(unsigned, Inspector*) { }
Inspector::Inspector() = default;
Inspector::~Inspector() = default;
+// LCOV_EXCL_START
bool Inspector::likes(Packet*) { return true; }
bool Inspector::get_buf(const char*, Packet*, InspectionBuffer&) { return true; }
class StreamSplitter* Inspector::get_splitter(bool) { return nullptr; }
+// LCOV_EXCL_STOP
// Stubs for search_tool.cc
SearchTool::~SearchTool() = default;
+// LCOV_EXCL_START
void SearchTool::add(const char*, unsigned, int, bool) { }
void SearchTool::add(const char*, unsigned, void*, bool) { }
void SearchTool::add(const uint8_t*, unsigned, int, bool) { }
void SearchTool::add(const uint8_t*, unsigned, void*, bool) { }
+// LCOV_EXCL_STOP
void SearchTool::prep() { }
// Stubs for util.cc
return p;
}
}
+// LCOV_EXCL_START
DiscoveryFilter::~DiscoveryFilter(){}
void show_stats(PegCount*, const PegInfo*, unsigned, const char*) { }
void show_stats(PegCount*, const PegInfo*, const IndexVec&, const char*, FILE*) { }
+// LCOV_EXCL_STOP
#ifndef SIP_UNIT_TEST
class AppIdInspector : public snort::Inspector
public:
AppIdInspector(AppIdModule&) { }
~AppIdInspector() override = default;
- void eval(Packet*) override { }
bool configure(snort::SnortConfig*) override;
+// LCOV_EXCL_START
+ void eval(Packet*) override { }
void show(const SnortConfig*) const override { }
void tinit() override { }
void tterm() override { }
+// LCOV_EXCL_STOP
private:
AppIdContext* ctxt = nullptr;
};
AppIdModule::AppIdModule()
: Module("a", "b") { }
AppIdModule::~AppIdModule() = default;
+
+// LCOV_EXCL_START
bool AppIdModule::begin(const char*, int, snort::SnortConfig*)
{
return false;
void AppIdModule::set_trace(const Trace*) const { }
const TraceOption* AppIdModule::get_trace_options() const { return nullptr; }
+// LCOV_EXCL_STOP
// Stubs for inspectors
unsigned AppIdSession::inspector_id = 0;
}
// Stubs for AppIdPegCounts
+// LCOV_EXCL_START
void AppIdPegCounts::update_service_count(AppId, bool) { }
void AppIdPegCounts::update_client_count(AppId, bool) { }
void AppIdPegCounts::inc_user_count(AppId) { }
int ServiceDiscovery::add_service_port(AppIdDetector*, const ServiceDetectorPort&)
{ return 0; }
+// LCOV_EXCL_STOP
OdpContext::OdpContext(const AppIdConfig&, snort::SnortConfig*)
{ }
{
mpsegrp = &mpse_group;
}
-void SearchTool::reload() { }
+void SearchTool::reload() { } // LCOV_EXCL_LINE
int SearchTool::find_all(const char*, unsigned, MpseMatch, bool, void*)
{
// Seg-fault will be observed if this is called without initializing pattern matchers
ctxt = &context;
return true;
}
+
+// LCOV_EXCL_START
void AppIdInspector::eval(Packet*) { }
void AppIdInspector::show(const SnortConfig*) const { }
void AppIdInspector::tinit() { }
void AppIdInspector::tterm() { }
void AppIdInspector::tear_down(SnortConfig*) { }
AppIdContext& AppIdInspector::get_ctxt() const { return *ctxt; }
+// LCOV_EXCL_STOP
+
AppIdInspector::~AppIdInspector() = default;
void AppIdContext::create_odp_ctxt()
void AppIdSession::publish_appid_event(AppidChangeBits&, const Packet&, bool, uint32_t) { }
AppIdDiscovery::~AppIdDiscovery() = default;
+
+// LCOV_EXCL_START
void ApplicationDescriptor::set_id(const Packet&, AppIdSession&, AppidSessionDirection,
AppId, AppidChangeBits&) { }
void ClientDiscovery::initialize(AppIdInspector&) { }
void ClientDiscovery::reload() { }
+// LCOV_EXCL_STOP
+
void AppIdDiscovery::register_detector(const string&, AppIdDetector*, IpProtocol) { }
+
+// LCOV_EXCL_START
void AppIdDiscovery::add_pattern_data(AppIdDetector*, snort::SearchTool&, int,
unsigned char const*, unsigned int, unsigned int) { }
void AppIdDiscovery::register_tcp_pattern(AppIdDetector*, unsigned char const*, unsigned int,
void AppIdDiscovery::register_udp_pattern(AppIdDetector*, unsigned char const*, unsigned int,
int, unsigned int) { }
int AppIdDiscovery::add_service_port(AppIdDetector*, ServiceDetectorPort const&) { return 0; }
-void AppIdModule::reset_stats() {}
+void AppIdModule::reset_stats() { }
+// LCOV_EXCL_STOP
+
DnsPatternMatchers::~DnsPatternMatchers() = default;
EfpCaPatternMatchers::~EfpCaPatternMatchers() = default;
SslPatternMatchers::~SslPatternMatchers() = default;
HttpPatternMatchers::~HttpPatternMatchers() = default;
ClientDetector::ClientDetector() { }
+
+// LCOV_EXCL_START
void ClientDetector::register_appid(int, unsigned int, OdpContext&) { }
int AppIdDetector::initialize(AppIdInspector&) { return 1; }
void AppIdDetector::reload() { }
void AppIdDetector::add_app(snort::Packet const&, AppIdSession&, AppidSessionDirection, int,
int, char const*, AppidChangeBits&) { }
void memory::MemoryCap::update_deallocations(size_t) { }
+// LCOV_EXCL_STOP
SipEvent::SipEvent(snort::Packet const* p, SIPMsg const*, SIP_DialogData const*) { this->p = p; }
SipEvent::~SipEvent() = default;
bool SipEvent::is_invite() const { return false; }
bool SipEvent::is_dialog_established() const { return false; }
-int SipPatternMatchers::get_client_from_ua(char const*, unsigned int, int&, char*&) { return 0; }
+int SipPatternMatchers::get_client_from_ua(char const*, unsigned int, int&, char*&) { return 0; } // LCOV_EXCL_LINE
void SipEventHandler::service_handler(SipEvent&, AppIdSession&, AppidChangeBits&) { }
SipUdpClientDetector* SipEventHandler::client = &cd;
bool AppIdOptionModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
+ assert(v.is("~"));
v.set_first_token();
string tok;
add_cpputest( tp_lib_handler_test
SOURCES
tp_lib_handler_test.cc
- ../../../network_inspectors/rna/test/rna_flow_mock.cc
+ ../../../network_inspectors/rna/test/rna_flow_stubs.cc
../tp_lib_handler.cc
LIBS
dl
#ifndef LOG_MESSAGE_MOCK
#define LOG_MESSAGE_MOCK
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
#include <cstdarg>
using namespace std;
else if ( v.is("mac") )
v.get_mac(host.mac_addr);
- else
- return false;
-
return true;
}
else if ( v.is("icmp6") )
Norm_Set(&config, NORM_ICMP6, v.get_bool());
- else
- return false;
-
return true;
}
else if ( v.is("group") )
config.group = v.get_int16();
- else
- return false;
-
return true;
}
return false;
}
}
- else
- return false;
-
return true;
}
{
return true;
}
- else
- return false;
-
return true;
}
else if ( v.is("icmp_window") )
config->icmp_window = v.get_uint32();
- else
- return false;
-
return true;
}
else if ( v.is("allowlist") )
conf->allowlist_path = v.get_string();
- else
- return false;
-
return true;
}
else
return false;
}
- else
- return false;
-
return true;
}
Value v1("rna.conf");
v1.set(Parameter::find(rna_params, "rna_conf_path"));
CHECK(mod.set(nullptr, v1, nullptr) == true);
-
- Value v3("dummy");
- CHECK(mod.set(nullptr, v3, nullptr) == false);
CHECK(mod.end("rna", 0, &sc) == true);
RnaModuleConfig* rc = mod.get_config();
../../../framework/parameter.cc
../../../host_tracker/host_cache.cc
../rna_fingerprint.cc
+ rna_module_mock.h
+ rna_module_stubs.h
$<TARGET_OBJECTS:catch_tests>
LIBS
${DNET_LIBRARIES}
namespace snort
{
-Module* ModuleManager::get_module(const char*)
-{ return nullptr; }
-
-char* snort_strdup(const char* s)
-{ return strdup(s); }
-
Module::Module(const char*, const char*, const Parameter*, bool) {}
-void Module::sum_stats(bool) {}
-void Module::show_stats() {}
-void Module::reset_stats() {}
-PegCount Module::get_global_count(char const*) const
-{ return 0; }
-void Module::show_interval_stats(std::vector<unsigned int, std::allocator<unsigned int> >&, FILE*)
-{}
-void LogMessage(const char*,...) {}
-void WarningMessage(const char*,...) {}
-SnortConfig::SnortConfig(SnortConfig const*) {}
-SnortConfig::~SnortConfig() = default;
-time_t packet_time() { return 0; }
-
-// tcp fingerprint functions
-bool TcpFpProcessor::push(const TcpFingerprint&) { return true; }
-void TcpFpProcessor::make_tcp_fp_tables(TCP_FP_MODE) { }
-const TcpFingerprint* TcpFpProcessor::get_tcp_fp(const FpTcpKey&, uint8_t, TCP_FP_MODE) const
-{ return nullptr; }
-const TcpFingerprint* TcpFpProcessor::get(const Packet*, RNAFlow*) const
-{ return nullptr; }
-TcpFpProcessor* get_tcp_fp_processor() { return nullptr; }
-void set_tcp_fp_processor(TcpFpProcessor*) { }
-
-TcpFingerprint::TcpFingerprint(const RawFingerprint&) { }
bool TcpFingerprint::operator==(const TcpFingerprint&) const { return true; }
-UaFpProcessor::~UaFpProcessor() = default;
-void UaFpProcessor::make_mpse(SnortConfig*) { }
-void UaFpProcessor::push(RawFingerprint const&) { }
-
-void UdpFpProcessor::push(RawFingerprint const&) { }
-
-SmbFingerprint::SmbFingerprint(const RawFingerprint&) { }
-bool SmbFingerprint::operator==(const SmbFingerprint&) const { return true; }
-bool SmbFpProcessor::push(SmbFingerprint const&) { return true; }
-
// inspector
class RnaInspector
{
} // end of namespace snort
-void snort::main_broadcast_command(snort::AnalyzerCommand*, ControlConn*) {}
-
static ControlConn s_ctrlcon(1, true);
ControlConn::ControlConn(int, bool) {}
ControlConn::~ControlConn() {}
-ControlConn* ControlConn::query_from_lua(const lua_State*) { return &s_ctrlcon; }
-bool ControlConn::respond(const char*, ...) { return true; }
-
-HostCacheMac* get_host_cache_mac() { return nullptr; }
-
-DataPurgeAC::~DataPurgeAC() = default;
-bool DataPurgeAC::execute(Analyzer&, void**) { return true;}
-
-void set_host_cache_mac(HostCacheMac*) { }
-
-Inspector* InspectorManager::get_inspector(const char*, bool, const SnortConfig*)
-{
- return nullptr;
-}
-
-void HostTracker::remove_flows() { }
#endif
+
--- /dev/null
+//--------------------------------------------------------------------------
+// Copyright (C) 2020-2021 Cisco and/or its affiliates. All rights reserved.
+//
+// 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. You may not use, modify or distribute
+// this program under any other version of the GNU General Public License.
+//
+// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//--------------------------------------------------------------------------
+
+// rna_module_stubs.h author Masud Hasan <mashasan@cisco.com>
+
+#ifndef RNA_MODULE_TEST_H
+#define RNA_MODULE_TEST_H
+
+namespace snort
+{
+Module* ModuleManager::get_module(const char*)
+{ return nullptr; }
+
+char* snort_strdup(const char* s)
+{ return strdup(s); }
+
+void Module::sum_stats(bool) {}
+void Module::show_stats() {}
+void Module::reset_stats() {}
+PegCount Module::get_global_count(char const*) const
+{ return 0; }
+void Module::show_interval_stats(std::vector<unsigned int, std::allocator<unsigned int> >&, FILE*)
+{}
+void LogMessage(const char*,...) {}
+void WarningMessage(const char*,...) {}
+SnortConfig::SnortConfig(SnortConfig const*) {}
+SnortConfig::~SnortConfig() = default;
+time_t packet_time() { return 0; }
+
+// tcp fingerprint functions
+bool TcpFpProcessor::push(const TcpFingerprint&) { return true; }
+void TcpFpProcessor::make_tcp_fp_tables(TCP_FP_MODE) { }
+const TcpFingerprint* TcpFpProcessor::get_tcp_fp(const FpTcpKey&, uint8_t, TCP_FP_MODE) const
+{ return nullptr; }
+const TcpFingerprint* TcpFpProcessor::get(const Packet*, RNAFlow*) const
+{ return nullptr; }
+TcpFpProcessor* get_tcp_fp_processor() { return nullptr; }
+void set_tcp_fp_processor(TcpFpProcessor*) { }
+
+TcpFingerprint::TcpFingerprint(const RawFingerprint&) { }
+
+UaFpProcessor::~UaFpProcessor() = default;
+void UaFpProcessor::make_mpse(SnortConfig*) { }
+void UaFpProcessor::push(RawFingerprint const&) { }
+
+void UdpFpProcessor::push(RawFingerprint const&) { }
+
+SmbFingerprint::SmbFingerprint(const RawFingerprint&) { }
+bool SmbFingerprint::operator==(const SmbFingerprint&) const { return true; }
+bool SmbFpProcessor::push(SmbFingerprint const&) { return true; }
+}
+
+void snort::main_broadcast_command(snort::AnalyzerCommand*, ControlConn*) {}
+
+ControlConn* ControlConn::query_from_lua(const lua_State*) { return &s_ctrlcon; }
+bool ControlConn::respond(const char*, ...) { return true; }
+
+HostCacheMac* get_host_cache_mac() { return nullptr; }
+
+DataPurgeAC::~DataPurgeAC() = default;
+bool DataPurgeAC::execute(Analyzer&, void**) { return true;}
+
+void set_host_cache_mac(HostCacheMac*) { }
+
+Inspector* InspectorManager::get_inspector(const char*, bool, const SnortConfig*)
+{
+ return nullptr;
+}
+
+void HostTracker::remove_flows() { }
+
+#endif
#include "../rna_module.cc"
#include "rna_module_mock.h"
+#include "rna_module_stubs.h"
// To avoid warnings between catch.hpp and UtestMacros.h macro definitions,
// since rna_module.cc has both catch and cpputest tests
#include "lua/lua.h"
#include "lua/lua_table.h"
-#include "lua/lua_util.h"
+#include "lua/lua_script.h"
#include "piglet_api.h"
#include "piglet_manager.h"
-
//--------------------------------------------------------------------------
// Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
//
return _search(T, n, match, context, current_state);
}
-void Mpse::search(MpseBatch& batch, MpseType mpse_type)
-{
- _search(batch, mpse_type);
-}
-
-void Mpse::_search(MpseBatch& batch, MpseType mpse_type)
-{
- int start_state;
-
- for ( auto& item : batch.items )
- {
- if (item.second.done)
- continue;
-
- item.second.error = false;
- item.second.matches = 0;
-
- for ( auto& so : item.second.so )
- {
- start_state = 0;
- switch (mpse_type)
- {
- case MPSE_TYPE_NORMAL:
- item.second.matches += so->normal_mpse->search(item.first.buf, item.first.len,
- batch.mf, batch.context, &start_state);
- break;
- case MPSE_TYPE_OFFLOAD:
- item.second.matches += so->offload_mpse->search(item.first.buf, item.first.len,
- batch.mf, batch.context, &start_state);
- break;
- }
- }
- item.second.done = true;
- }
-}
+void Mpse::search(MpseBatch&, MpseType) { }
+void Mpse::_search(MpseBatch&, MpseType) { }
}
else if ( v.is("max_unconnected_messages") )
conf->max_unconnected_messages = v.get_uint32();
- else
- return false;
-
return true;
}
bool CipAttributeModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_attr.validate(v.get_string(), RANGE);
}
bool CipClassModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_class.validate(v.get_string(), RANGE);
}
bool CipConnpathclassModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_cpc.validate(v.get_string(), RANGE);
}
bool CipEnipCommandModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_enip_cmd.validate(v.get_string(), RANGE);
}
bool CipInstanceModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_inst.validate(v.get_string(), RANGE);
}
bool CipServiceModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_serv.validate(v.get_string(), RANGE);
}
bool CipStatusModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~range") )
- return false;
-
+ assert(v.is("~range"));
return cip_status.validate(v.get_string(), RANGE);
}
bool Dce2TcpModule::set(const char*, Value& v, SnortConfig*)
{
- if (dce2_set_co_config(v,config.common))
- return true;
-
- return false;
+ return dce2_set_co_config(v,config.common);
}
void Dce2TcpModule::get_data(dce2TcpProtoConf& dce2_tcp_config)
token = DCE2_PruneWhiteSpace(token);
return DCE2_ParseIface(token, &uuid);
}
- else
- return false;
-
return true;
}
bool Dce2OpnumModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
+ assert(v.is("~"));
- if (v.get_string())
- {
- std::string tok (v.get_string());
- if ( tok[0] == '"' )
- tok.erase(0, 1);
+ std::string tok (v.get_string());
- if ( tok[tok.length()-1] == '"' )
- tok.erase(tok.length()-1, 1);
+ if ( tok[0] == '"' )
+ tok.erase(0, 1);
- char* s = snort_strdup(tok.c_str());
- DCE2_Ret status = DCE2_OpnumParse(s, &opnum);
- snort_free(s);
+ if ( tok[tok.length()-1] == '"' )
+ tok.erase(tok.length()-1, 1);
- if (status == DCE2_RET__SUCCESS)
- return true;
- }
+ char* s = snort_strdup(tok.c_str());
+ DCE2_Ret status = DCE2_OpnumParse(s, &opnum);
+ snort_free(s);
- return false;
+ return (status == DCE2_RET__SUCCESS);
}
ProfileStats* Dce2OpnumModule::get_profile() const
bool Dnp3Module::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("check_crc") )
- config.check_crc = v.get_bool();
-
- else
- return false;
-
+ assert(v.is("check_crc"));
+ config.check_crc = v.get_bool();
return true;
}
bool Dnp3FuncModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~"))
- return false;
+ assert(v.is("~"));
long n;
bool Dnp3IndModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
+ assert(v.is("~"));
flags = 0;
-
v.set_first_token();
std::string tok;
else if ( v.is("telnet_cmds") )
conf->telnet_cmds = v.get_bool();
- else
- return false;
-
return true;
}
else if ( v.is("telnet_cmds") )
conf->telnet_cmds = v.get_bool();
- else
- return false;
-
return true;
}
else if ( v.is("normalize") )
conf->normalize = v.get_bool();
- else
- return false;
-
return true;
}
bool GtpInfoModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
long n;
if ( v.strtol(n) )
bool GtpTypeModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
v.set_first_token();
std::string tok;
bool GtpVersionModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
version = v.get_uint8();
return true;
}
//--------------------------------------------------------------------------
// http2_huffman_state_machine.cc author Maya Dagon <mdagon@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "http2_huffman_state_machine.h"
const HuffmanEntry huffman_decode[HUFFMAN_LOOKUP_MAX+1] [UINT8_MAX+1] =
params->show_scan = val.get_bool();
}
#endif
- else
- {
- return false;
- }
return true;
}
//--------------------------------------------------------------------------
// http2_utils.cc author Maya Dagon <mdagon@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "http2_utils.h"
#include <cassert>
#ifndef HTTP2_UTILS_H
#define HTTP2_UTILS_H
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
#include "main/snort_types.h"
#include "service_inspectors/http_inspect/http_common.h"
//--------------------------------------------------------------------------
// http_buffer_info.cc author Brandon Stultz <brastult@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "hash/hash_key_operations.h"
#include "http_buffer_info.h"
params->show_scan = val.get_bool();
}
#endif
- else
- {
- return false;
- }
return true;
}
para_list.fragment = true;
sub_id = UC_FRAGMENT;
}
- else
- {
- return false;
- }
return true;
}
bool Iec104ApciTypeModule::set(const char*, Value& v, SnortConfig*)
{
- if (!v.is("~"))
- {
- return false;
- }
-
+ assert(v.is("~"));
long n;
if (v.strtol(n))
- {
apci_type = static_cast<uint8_t>(n);
- }
else if (get_apci_type(v.get_string(), n))
- {
apci_type = static_cast<uint8_t>(n);
- }
-
- else
- {
- return false;
- }
return true;
}
bool Iec104AsduFuncModule::set(const char*, Value& v, SnortConfig*)
{
- if (!v.is("~"))
- {
- return false;
- }
-
+ assert(v.is("~"));
long n;
if (v.strtol(n))
- {
func = static_cast<uint8_t>(n);
- }
else if (get_func(v.get_string(), n))
- {
func = static_cast<uint8_t>(n);
- }
-
- else
- {
- return false;
- }
return true;
}
else if ( v.is("uu_decode_depth") )
config->decode_conf.set_uu_depth(mime_value);
- else
- return false;
-
return true;
}
bool ModbusFuncModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
long n;
if ( v.strtol(n) )
else if ( get_func(v.get_string(), n) )
func = (uint8_t)n;
- else
- return false;
-
return true;
}
bool ModbusUnitModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
unit = v.get_uint8();
return true;
}
{
rule_cfg.create_service = v.get_bool();
}
- else
- return false;
-
return true;
}
else if ( v.is("uu_decode_depth") )
config->decode_conf.set_uu_depth(mime_value);
- else
- return false;
-
return true;
}
bool S7commplusFuncModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
long n;
if ( v.strtol(n) )
else if ( get_func(v.get_string(), n) )
func = static_cast<uint16_t>(n);
- else
- return false;
-
return true;
}
bool S7commplusOpcodeModule::set(const char*, Value& v, SnortConfig*)
{
- if ( !v.is("~") )
- return false;
-
+ assert(v.is("~"));
long n;
if ( v.strtol(n) )
else if ( get_opcode(v.get_string(), n) )
opcode = (uint8_t)n;
- else
- return false;
-
return true;
}
bool SipMethodModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("*method") )
+ assert(v.is("*method"));
+ const char* tok = v.get_string();
+
+ if (tok[0] == '!')
{
- const char* tok = v.get_string();
-
- if (tok[0] == '!')
- {
- negated = true;
- tok++;
- }
- else
- negated = false;
-
- /*Only one method is allowed with !*/
- if ( negated && (!methods.empty()) )
- ParseError("Only one method is allowed with ! for sip_method");
-
- std::string key = tok;
- std::transform(key.begin(), key.end(), key.begin(), ::toupper);
- methods[key] = negated;
+ negated = true;
+ tok++;
}
else
- return false;
+ negated = false;
+
+ /*Only one method is allowed with !*/
+ if ( negated && (!methods.empty()) )
+ ParseError("Only one method is allowed with ! for sip_method");
+
+ std::string key = tok;
+ std::transform(key.begin(), key.end(), key.begin(), ::toupper);
+ methods[key] = negated;
return true;
}
bool SipStatCodeModule::set(const char*, Value& v, SnortConfig*)
{
- if (num_tokens < SIP_NUM_STAT_CODE_MAX)
+ assert(v.is("*code"));
+
+ if (num_tokens >= SIP_NUM_STAT_CODE_MAX)
+ return false;
+
+ uint16_t statCode = v.get_uint16();
+
+ if ( (statCode >= NUM_OF_RESPONSE_TYPES) && (statCode < MIN_STAT_CODE) )
{
- if ( v.is("*code") )
- {
- uint16_t statCode = v.get_uint16();
-
- if ( (statCode >= NUM_OF_RESPONSE_TYPES) && (statCode < MIN_STAT_CODE) )
- {
- ParseError("Status code specified is not a single digit or a 3 digit number");
- return false;
- }
- ssod.stat_codes[num_tokens] = statCode;
- num_tokens++;
- }
- else
- return false;
- }
- else
+ ParseError("Status code specified is not a single digit or a 3 digit number");
return false;
+ }
+ ssod.stat_codes[num_tokens] = statCode;
+ num_tokens++;
return true;
}
else if ( v.is("methods") )
sip_methods = v.get_string();
- else
- return false;
-
return true;
}
else if ( v.is("xlink2state") )
config->xlink2state = (SMTPXlinkState)v.get_uint8();
- else
- return false;
-
return true;
}
else if ( v.is("max_server_version_len") )
conf->MaxServerVersionLen = v.get_uint8();
- else
- return false;
-
return true;
}
ssod.flags |= SSL_UNKNOWN_FLAG;
ssod.mask |= SSL_UNKNOWN_FLAG;
}
- else
- return false;
-
return true;
}
svod.flags |= SSL_VER_TLS12_FLAG;
svod.mask |= SSL_VER_TLS12_FLAG;
}
- else
- return false;
-
return true;
}
else if ( v.is("max_heartbeat_length") )
conf->max_heartbeat_len = v.get_uint16();
- else
- return false;
-
return true;
}
// ssl_splitter.cc author Steven Baigal <sbaigal@cisco.com>
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include "ssl_splitter.h"
#include <arpa/inet.h>
++*count;
return SFIP_SUCCESS;
-
- // FIXIT-L Insert new node into routing table
- // sfrt_add(node->ip,
}
sfip_var_t* sfvar_create_alias(const sfip_var_t* alias_from, const char* alias_to)
-if ( ENABLE_UNIT_TESTS )
- set(TEST_FILES sfrt_test.cc)
-endif()
-
add_library ( sfrt OBJECT
- sfrt.cc
- sfrt.h
- sfrt_dir.cc
- sfrt_dir.h
sfrt_flat.cc
sfrt_flat.h
sfrt_flat_dir.cc
sfrt_flat_dir.h
- ${TEST_FILES}
)
+++ /dev/null
-//--------------------------------------------------------------------------
-// Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
-// Copyright (C) 2006-2013 Sourcefire, Inc.
-//
-// 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. You may not use, modify or distribute
-// this program under any other version of the GNU General Public License.
-//
-// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
-//--------------------------------------------------------------------------
-
-/*
- * sfrt.cc author Adam Keeton <akeeton@sourcefire.com>
- * Thu July 20 10:16:26 EDT 2006
- *
- * Route implements two different routing table lookup mechanisms. The table
- * lookups have been adapted to return a void pointer so any information can
- * be associated with each CIDR block.
- *
- * As of this writing, the two methods used are Stefan Nilsson and Gunnar
- * Karlsson's LC-trie, and a multibit-trie method similar to Gupta et-al.'s
- * DIR-n-m. Presently, the LC-trie is used primarily for testing purposes as
- * the current implementation does not allow for fast dynamic inserts.
- *
- * The intended use is for a user to optionally specify large IP blocks and
- * then more specific information will be written into the routing tables
- * from RNA. Ideally, information will only move from less specific to more
- * specific. If a more general information is to overwrite existing entries,
- * the table should be freed and rebuilt.
- *
- *
- * Implementation:
- *
- * The routing tables associate an index into a "data" table with each CIDR.
- * Each entry in the data table stores a pointer to actual data. This
- * implementation was chosen so each routing entry only needs one word to
- * either index the data array, or point to another table.
- *
- * Inserts are performed by specifying a CIDR and a pointer to its associated
- * data. Since a new routing table entry may overwrite previous entries,
- * a flag selects whether the insert favors the most recent or favors the most
- * specific. Favoring most specific should be the default behavior. If
- * the user wishes to overwrite routing entries with more general data, the
- * table should be flushed, rather than using favor-most-recent.
- *
- * Before modifying the routing or data tables, the insert function performs a
- * lookup on the CIDR-to-be-inserted. If no entry or an entry *of differing
- * bit length* is found, the data is inserted into the data table, and its
- * index is used for the new routing table entry. If an entry is found that
- * is as specific as the new CIDR, the index stored points to where the new
- * data is written into the data table.
- *
- * If more specific CIDR blocks overwrote the data table, then the more
- * general routing table entries that were not overwritten will be referencing
- * the wrong data. Alternatively, less specific entries can only overwrite
- * existing routing table entries if favor-most-recent inserts are used.
- *
- * Because there is no quick way to clean the data-table if a user wishes to
- * use a favor-most-recent insert for more general data, the user should flush
- * the table with sfrt_free and create one anew. Alternatively, a small
- * memory leak occurs with the data table, as it will be storing pointers that
- * no routing table entry cares about.
- *
- *
- * The API calls that should be used are:
- * sfrt_new - create new table
- * sfrt_insert - insert entry
- * sfrt_lookup - lookup entry
- * sfrt_free - free table
-*/
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include "sfrt.h"
-
-#include "sfip/sf_cidr.h"
-#include "utils/util.h"
-
-using namespace snort;
-
-const char* rt_error_messages[] =
-{
- "Success",
- "Insert Failure",
- "Policy Table Exceeded",
- "Dir Insert Failure",
- "Dir Lookup Failure",
- "Memory Allocation Failure"
-};
-
-static inline int allocateTableIndex(table_t* table);
-
-/* Create new lookup table
- * @param table_type Type of table. Uses the types enumeration in route.h
- * @param ip_type IPv4 or IPv6. Uses the types enumeration in route.h
- * @param data_size Max number of unique data entries
- *
- * Returns the new table. */
-table_t* sfrt_new(char table_type, char ip_type, long data_size, uint32_t mem_cap)
-{
- table_t* table = (table_t*)snort_alloc(sizeof(table_t));
-
- /* If this limit is exceeded, there will be no way to distinguish
- * between pointers and indices into the data table. Only
- * applies to DIR-n-m. */
-#if SIZEOF_LONG_INT == 8
- if (data_size >= 0x800000000000000)
-#else
- if (data_size >= 0x8000000)
-#endif
- {
- snort_free(table);
- return nullptr;
- }
-
- /* mem_cap is specified in megabytes, but internally uses bytes. Convert */
- mem_cap *= 1024*1024;
-
- /* Maximum allowable number of stored entries */
- table->max_size = data_size;
- table->lastAllocatedIndex = 0;
-
- table->data = (GENERIC*)snort_calloc(sizeof(GENERIC) * table->max_size);
- table->allocated = sizeof(table_t) + sizeof(GENERIC) * table->max_size;
-
- table->ip_type = ip_type;
- table->table_type = table_type;
-
- /* This will point to the actual table lookup algorithm */
- table->rt = nullptr;
- table->rt6 = nullptr;
-
- /* index 0 will be used for failed lookups, so set this to 1 */
- table->num_ent = 1;
-
- switch (table_type)
- {
- /* Setup DIR-n-m table */
- case DIR_24_8:
- case DIR_16x2:
- case DIR_16_8x2:
- case DIR_16_4x4:
- case DIR_8x4:
- case DIR_4x8:
- case DIR_2x16:
- case DIR_16_4x4_16x5_4x4:
- case DIR_16x7_4x4:
- case DIR_16x8:
- case DIR_8x16:
- table->insert = sfrt_dir_insert;
- table->lookup = sfrt_dir_lookup;
- table->free = sfrt_dir_free;
- table->usage = sfrt_dir_usage;
- table->print = sfrt_dir_print;
- table->remove = sfrt_dir_remove;
-
- break;
-
- default:
- snort_free(table->data);
- snort_free(table);
- return nullptr;
- }
-
- /* Allocate the user-specified DIR-n-m table */
- switch (table_type)
- {
- case DIR_24_8:
- table->rt = sfrt_dir_new(mem_cap, 2, 24,8);
- break;
- case DIR_16x2:
- table->rt = sfrt_dir_new(mem_cap, 2, 16,16);
- break;
- case DIR_16_8x2:
- table->rt = sfrt_dir_new(mem_cap, 3, 16,8,8);
- break;
- case DIR_16_4x4:
- table->rt = sfrt_dir_new(mem_cap, 5, 16,4,4,4,4);
- break;
- case DIR_8x4:
- table->rt = sfrt_dir_new(mem_cap, 4, 8,8,8,8);
- break;
- /* There is no reason to use 4x8 except for benchmarking and
- * comparison purposes. */
- case DIR_4x8:
- table->rt = sfrt_dir_new(mem_cap, 8, 4,4,4,4,4,4,4,4);
- break;
- /* There is no reason to use 2x16 except for benchmarking and
- * comparison purposes. */
- case DIR_2x16:
- table->rt = sfrt_dir_new(mem_cap, 16,
- 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2);
- break;
- case DIR_16_4x4_16x5_4x4:
- table->rt = sfrt_dir_new(mem_cap, 5, 16,4,4,4,4);
- table->rt6 = sfrt_dir_new(mem_cap, 14, 16,4,4,4,4,16,16,16,16,16,4,4,4,4);
- break;
- case DIR_16x7_4x4:
- table->rt = sfrt_dir_new(mem_cap, 5, 16,4,4,4,4);
- table->rt6 = sfrt_dir_new(mem_cap, 11, 16,16,16,16,16,16,16,4,4,4,4);
- break;
- case DIR_16x8:
- table->rt = sfrt_dir_new(mem_cap, 2, 16,16);
- table->rt6 = sfrt_dir_new(mem_cap, 8, 16,16,16,16,16,16,16,16);
- break;
- case DIR_8x16:
- table->rt = sfrt_dir_new(mem_cap, 4, 16,8,4,4);
- table->rt6 = sfrt_dir_new(mem_cap, 16,
- 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8);
- break;
- }
-
- if ((!table->rt) || (!table->rt6))
- {
- if (table->rt)
- table->free(table->rt);
- if (table->rt6)
- table->free(table->rt6);
- snort_free(table->data);
- snort_free(table);
- return nullptr;
- }
-
- return table;
-}
-
-/* Free lookup table */
-void sfrt_free(table_t* table)
-{
- if (!table)
- {
- /* What are you calling me for? */
- return;
- }
-
- if (!table->data)
- {
- /* This really really should not have happened */
- }
- else
- {
- snort_free(table->data);
- }
-
- if (!table->rt)
- {
- /* This should not have happened either */
- }
- else
- {
- table->free(table->rt);
- }
-
- if (!table->rt6)
- {
- /* This should not have happened either */
- }
- else
- {
- table->free(table->rt6);
- }
-
- snort_free(table);
-}
-
-/* Perform a lookup on value contained in "ip" */
-GENERIC sfrt_lookup(const SfIp* ip, table_t* table)
-{
- tuple_t tuple;
- const uint32_t* addr;
- int numAddrDwords;
- void* rt ;
-
- if (!ip || !table || !table->lookup)
- return nullptr;
-
- if (ip->is_ip4())
- {
- addr = ip->get_ip4_ptr();
- numAddrDwords = 1;
- rt = table->rt;
- }
- else
- {
- addr = ip->get_ip6_ptr();
- numAddrDwords = 4;
- rt = table->rt6;
- }
-
- if (!rt)
- return nullptr;
-
- tuple = table->lookup(addr, numAddrDwords, rt);
-
- if (tuple.index >= table->max_size)
- return nullptr;
-
- return table->data[tuple.index];
-}
-
-void sfrt_cleanup(table_t* table, sfrt_iterator_callback cleanup_func)
-{
- uint32_t index, count;
-
- if (!table)
- return;
-
- for (index = 0, count = 0;
- index < table->max_size;
- index++)
- {
- if (table->data[index])
- {
- cleanup_func(table->data[index]);
-
- /* cleanup_func is supposed to free memory associated with this
- * table->data[index]. Set that to null.
- */
- table->data[index] = nullptr;
-
- if (++count == table->num_ent)
- break;
- }
- }
-}
-
-GENERIC sfrt_search(const SfIp* ip, unsigned char len, table_t* table)
-{
- const uint32_t* addr;
- int numAddrDwords;
- tuple_t tuple;
- void* rt;
-
- if ((ip == nullptr) || (table == nullptr) || (len == 0))
- return nullptr;
-
- if (ip->is_ip4())
- {
- addr = ip->get_ip4_ptr();
- numAddrDwords = 1;
- rt = table->rt;
- }
- else if (ip->is_ip6())
- {
- addr = ip->get_ip6_ptr();
- numAddrDwords = 4;
- rt = table->rt6;
- }
- else
- return nullptr;
-
- // FIXIT-RC IPv6 not yet supported by sfrt?
- if (table->ip_type == IPv6)
- return nullptr;
-
- if ( (table->ip_type == IPv4 && len > 32) ||
- (table->ip_type == IPv6 && len > 128) )
- {
- return nullptr;
- }
-
- tuple = table->lookup(addr, numAddrDwords, rt);
-
- if (tuple.length != len)
- return nullptr;
-
- return table->data[tuple.index];
-}
-
-/* Insert "ip", of length "len", into "table", and have it point to "ptr" */
-int sfrt_insert(SfCidr* cidr, unsigned char len, GENERIC ptr,
- int behavior, table_t* table)
-{
- const uint32_t* addr;
- const SfIp* ip;
- int numAddrDwords;
- int index;
- int newIndex = 0;
- int res;
- tuple_t tuple;
- void* rt;
-
- if (!cidr)
- {
- return RT_INSERT_FAILURE;
- }
-
- if (len == 0)
- return RT_INSERT_FAILURE;
-
- if (!table || !table->insert || !table->data || !table->lookup)
- {
- return RT_INSERT_FAILURE;
- }
-
- if ( (table->ip_type == IPv4 && len > 32) ||
- (table->ip_type == IPv6 && len > 128) )
- {
- return RT_INSERT_FAILURE;
- }
-
- /* Check if we can reuse an existing data table entry by
- * seeing if there is an existing entry with the same length. */
- ip = cidr->get_addr();
- if (ip->is_ip4())
- {
- if (len < 96)
- return RT_INSERT_FAILURE;
- len -= 96;
- addr = ip->get_ip4_ptr();
- numAddrDwords = 1;
- rt = table->rt;
- }
- else if (ip->is_ip6())
- {
- addr = ip->get_ip6_ptr();
- numAddrDwords = 4;
- rt = table->rt6;
- }
- else
- return RT_INSERT_FAILURE;
-
- tuple = table->lookup(addr, numAddrDwords, rt);
-
- if (tuple.length != len)
- {
- if ( table->num_ent >= table->max_size)
- {
- return RT_POLICY_TABLE_EXCEEDED;
- }
-
- index = newIndex = allocateTableIndex(table);
- if (!index)
- return RT_POLICY_TABLE_EXCEEDED;
- }
- else
- {
- index = tuple.index;
- }
-
- /* The actual value that is looked-up is an index
- * into the data table. */
- res = table->insert(addr, numAddrDwords, len, index, behavior, rt);
-
- if ((res == RT_SUCCESS) && newIndex)
- {
- table->num_ent++;
- table->data[ index ] = ptr;
- }
-
- return res;
-}
-/** Pretty print table
- * Pretty print sfrt table.
- * @param table - routing table.
- */
-void sfrt_print(table_t* table)
-{
- if (!table || !table->print )
- {
- return;
- }
-
- if (table->rt)
- table->print(table->rt);
- if (table->rt6)
- table->print(table->rt6);
-}
-
-uint32_t sfrt_num_entries(table_t* table)
-{
- if (!table || !table->rt || !table->allocated)
- {
- return 0;
- }
-
- /* There is always a root node, so subtract 1 for it */
- return table->num_ent - 1;
-}
-
-uint32_t sfrt_usage(table_t* table)
-{
- uint32_t usage;
- if (!table || !table->rt || !table->allocated || !table->usage)
- {
- return 0;
- }
-
- usage = table->allocated + table->usage(table->rt);
-
- if (table->rt6)
- {
- usage += table->usage(table->rt6);
- }
-
- return usage;
-}
-
-/** Remove subnet from sfrt table.
- * Remove subnet identified by ip/len and return associated data.
- * @param ip - IP address
- * @param len - length of netmask
- * @param ptr - void ** that is set to value associated with subnet
- * @param behavior - RT_FAVOR_SPECIFIC or RT_FAVOR_TIME
- * @note - For RT_FAVOR_TIME behavior, if partial subnet is removed then table->data[x] is nulled. Any remaining entries
- * will then point to null data. This can cause hung or crosslinked data. RT_FAVOR_SPECIFIC does not have this drawback.
- * hung or crosslinked entries.
- */
-int sfrt_remove(SfCidr* cidr, unsigned char len, GENERIC* ptr,
- int behavior, table_t* table)
-{
- const uint32_t* addr;
- const SfIp* ip;
- int numAddrDwords;
- int index;
- void* rt;
-
- if (!cidr)
- {
- return RT_REMOVE_FAILURE;
- }
-
- if (len == 0)
- return RT_REMOVE_FAILURE;
-
- if (!table || !table->data || !table->remove || !table->lookup )
- return RT_REMOVE_FAILURE;
-
- if ( (table->ip_type == IPv4 && len > 32) ||
- (table->ip_type == IPv6 && len > 128) )
- {
- return RT_REMOVE_FAILURE;
- }
-
- ip = cidr->get_addr();
- if (ip->is_ip4())
- {
- if (len < 96)
- return RT_REMOVE_FAILURE;
- len -= 96;
- addr = ip->get_ip4_ptr();
- numAddrDwords = 1;
- rt = table->rt;
- }
- else if (ip->is_ip6())
- {
- addr = ip->get_ip6_ptr();
- numAddrDwords = 4;
- rt = table->rt6;
- }
- else
- return RT_REMOVE_FAILURE;
-
- /* The actual value that is looked-up is an index
- * into the data table. */
- index = table->remove(addr, numAddrDwords, len, behavior, rt);
-
- /* Remove value into policy table. See TBD in function header*/
- if (index)
- {
- *ptr = table->data[ index ];
- table->data[ index ] = nullptr;
- table->num_ent--;
- }
-
- return RT_SUCCESS;
-}
-
-/**allocate first unused index value. With delete operation, index values can be non-contiguous.
- * Index 0 is error in this function but this is valid entry in table->data that is used
- * for failure case. Calling function must check for 0 and take appropriate error action.
- */
-static inline int allocateTableIndex(table_t* table)
-{
- uint32_t index;
-
- // 0 is special index for failed entries.
- for (index = table->lastAllocatedIndex+1;
- index != table->lastAllocatedIndex;
- index = (index+1) % table->max_size)
- {
- if (index && !table->data[index])
- {
- table->lastAllocatedIndex = index;
- return index;
- }
- }
- return 0;
-}
-
word length;
};
-#include "sfrt/sfrt_dir.h"
-
enum types
{
+#if 0
+ // supporting code for these types (and RT_FAVOR_* below) is
+ // disabled since it is not used. not deleting in case we need
+ // switch types at some point. see sfrt_*.cc.
DIR_24_8,
DIR_16x2,
DIR_16_8x2,
DIR_16_4x4_16x5_4x4,
DIR_16x7_4x4,
DIR_16x8,
+#endif
DIR_8x16,
IPv4,
IPv6
enum
{
+#if 0
RT_FAVOR_TIME,
RT_FAVOR_SPECIFIC,
+#endif
RT_FAVOR_ALL
};
-extern const char* rt_error_messages[];
-
-typedef int (* table_insert)(
- const uint32_t* addr, int numAddrDwords, int len, word index, int behavior, GENERIC);
-
-typedef word (* table_remove)(
- const uint32_t* addr, int numAddrDwords, int len, int behavior, GENERIC);
-
-typedef tuple_t (* table_lookup)(const uint32_t* addr, int numAddrDwords, GENERIC);
-
-typedef uint32_t (* table_usage)(GENERIC);
-typedef void (* table_print)(GENERIC);
-typedef void (* table_free)(GENERIC);
-
-// Master table struct. Abstracts DIR and LC-trie methods
-struct table_t
-{
- GENERIC* data; // data table. Each IP points to an entry here
- uint32_t num_ent; // Number of entries in the policy table
- uint32_t max_size; // Max size of policies array
- uint32_t lastAllocatedIndex; // Index allocated last. Search for unused index
- // starts from this value and then wraps around at max_size.
- char ip_type; // Only IPs of this family will be used
- char table_type;
- uint32_t allocated;
-
- void* rt; // Actual "routing" table
- void* rt6; // Actual "routing" table
-
- table_insert insert;
- table_remove remove;
- table_lookup lookup;
- table_usage usage;
- table_print print;
- table_free free;
-};
-
-// Abstracted routing table API
-table_t* sfrt_new(char type, char ip_type, long data_size, uint32_t mem_cap);
-void sfrt_free(table_t*);
-
-GENERIC sfrt_lookup(const snort::SfIp*, table_t*);
-GENERIC sfrt_search(const snort::SfIp*, unsigned char len, table_t*);
-
-typedef void (* sfrt_iterator_callback)(void*);
-void sfrt_cleanup(table_t*, sfrt_iterator_callback);
-
-int sfrt_insert(snort::SfCidr*, unsigned char len, GENERIC, int behavior, table_t*);
-int sfrt_remove(snort::SfCidr*, unsigned char len, GENERIC*, int behavior, table_t*);
-
-uint32_t sfrt_usage(table_t*);
-void sfrt_print(table_t*);
-uint32_t sfrt_num_entries(table_t*);
-
#endif
+++ /dev/null
-//--------------------------------------------------------------------------
-// Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
-// Copyright (C) 2006-2013 Sourcefire, Inc.
-//
-// 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. You may not use, modify or distribute
-// this program under any other version of the GNU General Public License.
-//
-// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
-//--------------------------------------------------------------------------
-
-/*
- * @file sfdir.c
- * @author Adam Keeton <akeeton@sourcefire.com>
- * @date Thu July 20 10:16:26 EDT 2006
- *
- * The implementation uses an multibit-trie that is similar to Gupta et-al's
- * DIR-n-m.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include "sfrt.h" // FIXIT-L these includes are circular
-#include "sfrt_dir.h"
-
-#include <cstdarg>
-
-#include "utils/util.h"
-
-typedef struct
-{
- const uint32_t* addr;
- int bits;
-} IPLOOKUP;
-
-/* Create new "sub" table of 2^width entries */
-static dir_sub_table_t* _sub_table_new(dir_table_t* root, uint32_t dimension,
- uint32_t prefill, uint32_t bit_length)
-{
- int width = root->dimensions[dimension];
- int len = 1 << width;
- int index;
- dir_sub_table_t* sub;
-
- /* Check if creating this node will exceed the memory cap.
- * The symbols in the conditional (other than cap), come from the
- * allocs below. */
- if ( root->mem_cap < ( root->allocated +
- sizeof(dir_sub_table_t) +
- sizeof(word) * len + len ) ||
- bit_length > 128)
- {
- return nullptr;
- }
-
- /* Set up the initial prefilled "sub table" */
- sub = (dir_sub_table_t*)snort_alloc(sizeof(dir_sub_table_t));
-
- /* This keeps the width readily available rather than recalculating it
- * from the number of entries during an insert or lookup */
- sub->width = width;
-
- /* need 2^sub->width entries */
- sub->num_entries = len;
- sub->entries = (word*)snort_alloc(sizeof(word) * sub->num_entries);
-
- /* A "length" needs to be stored with each entry above. The length refers
- * to how specific the insertion that set the entry was. It is necessary
- * so that the entry is not overwritten by less general routing
- * information if "RT_FAVOR_SPECIFIC" insertions are being performed. */
- sub->lengths = (uint8_t*)snort_alloc(sub->num_entries);
-
- /* Can't use memset here since prefill is multibyte */
- for (index = 0; index < sub->num_entries; index++)
- {
- sub->entries[index] = prefill;
- sub->lengths[index] = (uint8_t)bit_length;
- }
-
- sub->cur_num = 0;
-
- if (prefill)
- sub->filledEntries = sub->num_entries;
- else
- sub->filledEntries = 0;
-
- root->allocated += sizeof(dir_sub_table_t) + sizeof(word) * sub->num_entries +
- sub->num_entries;
-
- root->cur_num++;
-
- return sub;
-}
-
-/* Create new dir-n-m root table with 'count' depth */
-dir_table_t* sfrt_dir_new(uint32_t mem_cap, int count,...)
-{
- dir_table_t* table = (dir_table_t*)snort_alloc(sizeof(dir_table_t));
-
- table->allocated = 0;
- table->dimensions = (int*)snort_alloc(sizeof(int)*count);
- table->dim_size = count;
-
- va_list ap;
- va_start(ap, count);
-
- for (int index=0; index < count; index++)
- table->dimensions[index] = va_arg(ap, int);
-
- va_end(ap);
-
- table->mem_cap = mem_cap;
-
- table->cur_num = 0;
-
- table->sub_table = _sub_table_new(table, 0, 0, 0);
-
- if (!table->sub_table)
- {
- snort_free(table->dimensions);
- snort_free(table);
- return nullptr;
- }
-
- table->allocated += sizeof(dir_table_t) + sizeof(int)*count;
-
- return table;
-}
-
-/* Traverse "sub" tables, freeing each */
-static void _sub_table_free(uint32_t* allocated, dir_sub_table_t* sub)
-{
- int index;
-
- sub->cur_num--;
-
- for (index=0; index < sub->num_entries; index++)
- {
- /* The following condition will only be true if
- * this entry is a pointer */
- if ( !sub->lengths[index] && sub->entries[index] )
- {
- _sub_table_free(allocated, (dir_sub_table_t*)sub->entries[index]);
- }
- }
-
- if (sub->entries)
- {
- /* This probably does not need to be checked
- * since if it was not allocated, we would have errored out
- * in _sub_table_new */
- snort_free(sub->entries);
-
- *allocated -= sizeof(word) * sub->num_entries;
- }
-
- if (sub->lengths)
- {
- /* This probably does not need to be checked
- * since if it was not allocated, we would have errored out
- * in _sub_table_new */
- snort_free(sub->lengths);
-
- *allocated -= sub->num_entries;
- }
-
- snort_free(sub);
-
- *allocated -= sizeof(dir_sub_table_t);
-}
-
-/* Free the DIR-n-m structure */
-void sfrt_dir_free(void* tbl)
-{
- dir_table_t* table = (dir_table_t*)tbl;
-
- if (!table)
- {
- return;
- }
-
- if (table->sub_table)
- {
- _sub_table_free(&table->allocated, table->sub_table);
- }
-
- if (table->dimensions)
- {
- snort_free(table->dimensions);
- }
-
- snort_free(table);
-}
-
-static inline void _dir_fill_all(uint32_t* allocated, uint32_t index, uint32_t fill,
- word length, uint32_t val, dir_sub_table_t* table)
-{
- /* Fill entries */
- for (; index < fill; index++)
- {
- /* Before overwriting this entry, verify there's not an existing
- * pointer ... otherwise free it to avoid a huge memory leak. */
- if (table->entries[index])
- {
- if (!table->lengths[index])
- {
- _sub_table_free(allocated, (dir_sub_table_t*)table->entries[index]);
- }
- }
- else
- {
- table->filledEntries++;
- }
-
- table->entries[index] = val;
- table->lengths[index] = (uint8_t)length;
- }
-}
-
-static inline void _dir_fill_less_specific(int index, int fill,
- word length, uint32_t val, dir_sub_table_t* table)
-{
- /* Fill entries */
- for (; index < fill; index++)
- {
- /* If we encounter a pointer, and we're inserting at this level, we
- * automatically know that this entry refers to more specific
- * information. However, there might only be one more specific entry
- * in the entire block, meaning the rest must be filled.
- *
- * For instance, imagine a 24-8 with 1.2.3/24 -> A and 1.2.3.4/32 -> B
- * There will be a pointer at 1.2.3 in the first table. The second
- * table needs to have 255 entries pointing A, and 1 entry pointing to
- * B.
- *
- * Therefore, recurse to this next level. */
-
- if ( !table->lengths[index] && table->entries[index])
- {
- dir_sub_table_t* next = (dir_sub_table_t*)table->entries[index];
- _dir_fill_less_specific(0, 1 << next->width, length, val, next);
- }
- else if (length >= (word)table->lengths[index])
- {
- if (!table->entries[index])
- {
- table->filledEntries++;
- }
- table->entries[index] = val;
- table->lengths[index] = (char)length;
- }
- }
-}
-
-/*Remove entries all this level and discard any more specific entries.
- *
- * @note RT_FAVOR_TIME behavior can cause hung or crosslinked entries if part of a subnet
- * (which was added) are deleted. Same issue is there when a more general subnet overwrites
- * a specific subnet. table->data[] entry for more specific subnet is not cleared.
- *
- * @note RT_FAVOR_TIME can cause orphaned table->data[] entries if the entire subnet
- * is replaced by more specific subnets.
- */
-static inline uint32_t _dir_remove_all(uint32_t* allocated, uint32_t index, uint32_t fill,
- word length, dir_sub_table_t* table)
-{
- uint32_t valueIndex = 0;
-
- /* Fill entries */
- for (; index < fill; index++)
- {
- /* Before overwriting this entry, verify there's not an existing
- * pointer ... otherwise free it to avoid a huge memory leak. */
- if (table->entries[index])
- {
- if (!table->lengths[index])
- {
- _sub_table_free(allocated, (dir_sub_table_t*)table->entries[index]);
- }
-
- if (length == (word)table->lengths[index])
- {
- valueIndex = table->entries[index];
- }
-
- table->filledEntries--;
-
- //zero value here works since sfrt uses 0 for failed entries.
- table->entries[index] = 0;
- table->lengths[index] = 0;
- }
- }
-
- return valueIndex;
-}
-
-/**Remove entries which match in address/length in all subtables.
- * @note RT_FAVOR_SPECIFIC can cause orphaned table->data[] entries if the entire subnet
- * is replaced by more specific subnets.
- */
-static inline uint32_t _dir_remove_less_specific(uint32_t* allocated, int index, int fill,
- word length, dir_sub_table_t* table)
-{
- uint32_t valueIndexRet = 0;
-
- for (; index < fill; index++)
- {
- if ( !table->lengths[index] && table->entries[index])
- {
- dir_sub_table_t* next = (dir_sub_table_t*)table->entries[index];
- uint32_t valueIndex = _dir_remove_less_specific(allocated, 0, 1 << next->width, length, next);
- if (valueIndex)
- {
- valueIndexRet = valueIndex;
- }
-
- if (!next->filledEntries) //table can be collapsed.
- {
- _sub_table_free(allocated, next);
- table->entries[index] = 0;
- table->lengths[index] = 0;
- table->filledEntries--;
- }
- }
- else if (length == (word)table->lengths[index])
- {
- if (table->entries[index])
- {
- table->filledEntries--;
- valueIndexRet = table->entries[index];
- }
- table->entries[index] = 0;
- table->lengths[index] = 0;
- }
- }
-
- return valueIndexRet;
-}
-
-/* Sub table insertion
- * This is called by dir_insert and recursively to find the the sub table
- * that should house the value "ptr"
- * @param ip IP address structure
- * @param cur_len Number of bits of the IP left at this depth
- * @param length Number of bits of the IP used to specify this CIDR
- * @param ptr Information to be associated with this IP range
- * @param master_table The table that describes all, returned by dir_new */
-static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, GENERIC ptr,
- int current_depth, int behavior,
- dir_sub_table_t* sub_table, dir_table_t* root_table)
-{
- word index;
- {
- uint32_t local_index, i;
- /* need to handle bits usage across multiple 32bit vals within IPv6. */
- if (ip->bits < 32)
- {
- i=0;
- }
- else if (ip->bits < 64)
- {
- i=1;
- }
- else if (ip->bits < 96)
- {
- i=2;
- }
- else
- {
- i=3;
- }
- local_index = ip->addr[i] << (ip->bits % 32);
- index = local_index >> (sizeof(local_index) * 8 - sub_table->width);
- }
-
- /* Check if this is the last table to traverse to */
- if (sub_table->width >= cur_len)
- {
- /* Calculate how many entries need to be filled
- * in this table. If the table is 24 bits wide, and the entry
- * is 20 bytes long, 2^4 entries need to be filled. */
- uint32_t fill = 1 << (sub_table->width - cur_len);
-
- index = (index >> (sub_table->width - cur_len)) <<
- (sub_table->width - cur_len);
-
- fill += index;
-
- /* Favor most recent CIDR */
- if (behavior == RT_FAVOR_TIME)
- {
- _dir_fill_all(&root_table->allocated, index, fill, length,
- (word)ptr, sub_table);
- }
- /* Fill over less specific CIDR */
- else
- {
- _dir_fill_less_specific(index, fill, length, (word)ptr, sub_table);
- }
- }
- /* Need to traverse to a sub-table */
- else
- {
- dir_sub_table_t* next_sub =
- (dir_sub_table_t*)sub_table->entries[index];
-
- /* Check if we need to alloc a new sub table.
- * If next_sub was 0/null, there's no entry at this index
- * If the length is non-zero, there is an entry */
- if (!next_sub || sub_table->lengths[index])
- {
- if ( root_table->dim_size <= current_depth )
- {
- return RT_INSERT_FAILURE;
- }
-
- sub_table->entries[index] =
- (word)_sub_table_new(root_table, current_depth+1,
- (word)next_sub, sub_table->lengths[index]);
-
- if (!next_sub)
- {
- sub_table->filledEntries++;
- }
-
- sub_table->cur_num++;
-
- sub_table->lengths[index] = 0;
-
- next_sub = (dir_sub_table_t*)sub_table->entries[index];
-
- if (!next_sub)
- {
- return MEM_ALLOC_FAILURE;
- }
- }
- /* Recurse to next level. Rightshift off appropriate number of
- * bits and update the length accordingly. */
- ip->bits += sub_table->width;
- return (_dir_sub_insert(ip, length,
- cur_len - sub_table->width, ptr, current_depth+1,
- behavior, next_sub, root_table));
- }
-
- return RT_SUCCESS;
-}
-
-/* Insert entry into DIR-n-m tables */
-int sfrt_dir_insert(const uint32_t* addr, int /* numAddrDwords */, int len, word data_index,
- int behavior, void* table)
-{
- dir_table_t* root = (dir_table_t*)table;
- uint32_t h_addr[4];
- IPLOOKUP iplu;
- iplu.addr = h_addr;
- iplu.bits = 0;
-
- /* Validate arguments */
- if (!root || !root->sub_table)
- {
- return DIR_INSERT_FAILURE;
- }
-
- h_addr[0] = ntohl(addr[0]);
- if (len > 96)
- {
- h_addr[1] = ntohl(addr[1]);
- h_addr[2] = ntohl(addr[2]);
- h_addr[3] = ntohl(addr[3]);
- }
- else if (len > 64)
- {
- h_addr[1] = ntohl(addr[1]);
- h_addr[2] = ntohl(addr[2]);
- h_addr[3] = 0;
- }
- else if (len > 32)
- {
- h_addr[1] = ntohl(addr[1]);
- h_addr[2] = 0;
- h_addr[3] = 0;
- }
- else
- {
- h_addr[1] = 0;
- h_addr[2] = 0;
- h_addr[3] = 0;
- }
-
- /* Find the sub table in which to insert */
- return _dir_sub_insert(&iplu, len, len, (GENERIC)data_index,
- 0, behavior, root->sub_table, root);
-}
-
-/* Traverse sub tables looking for match
- Called by dir_lookup and recursively */
-static tuple_t _dir_sub_lookup(IPLOOKUP* ip, dir_sub_table_t* table)
-{
- word index;
- {
- uint32_t local_index, i;
- /* need to handle bits usage across multiple 32bit vals within IPv6. */
- if (ip->bits < 32 )
- {
- i=0;
- }
- else if (ip->bits < 64)
- {
- i=1;
- }
- else if (ip->bits < 96)
- {
- i=2;
- }
- else
- {
- i=3;
- }
- local_index = ip->addr[i] << (ip->bits % 32);
- index = local_index >> (sizeof(local_index) * 8 - table->width);
- }
-
- if ( !table->entries[index] || table->lengths[index] )
- {
- tuple_t ret;
- ret.index = table->entries[index];
- ret.length = (word)table->lengths[index];
-
- return ret;
- }
-
- ip->bits += table->width;
- return _dir_sub_lookup(ip, (dir_sub_table_t*)table->entries[index]);
-}
-
-/* Lookup information associated with the value "ip" */
-tuple_t sfrt_dir_lookup(const uint32_t* addr, int numAddrDwords, void* tbl)
-{
- dir_table_t* root = (dir_table_t*)tbl;
- uint32_t h_addr[4];
- int i;
- IPLOOKUP iplu;
- iplu.addr = h_addr;
- iplu.bits = 0;
-
- if (!root || !root->sub_table || numAddrDwords < 1)
- {
- tuple_t ret = { 0, 0 };
-
- return ret;
- }
-
- for (i= 0 ; i < numAddrDwords; i++)
- h_addr[i] = ntohl(addr[i]);
-
- return _dir_sub_lookup(&iplu, root->sub_table);
-}
-
-uint32_t sfrt_dir_usage(void* table)
-{
- if (!table)
- {
- return 0;
- }
-
- return ((dir_table_t*)(table))->allocated;
-}
-
-static void _sub_table_print(dir_sub_table_t* sub, uint32_t level, dir_table_t* table)
-{
- int index;
-
- char label[100];
-
- memset(label, ' ', sizeof(label));
- label[level*5] = '\0';
-
- printf("%sCurrent Nodes: %d, Filled Entries: %d, table Width: %d\n", label, sub->cur_num,
- sub->filledEntries, sub->width);
- for (index=0; index < sub->num_entries; index++)
- {
- if (sub->lengths[index] || sub->entries[index])
- printf("%sIndex: %d, Length: %d, dataIndex: %u\n", label, index, sub->lengths[index],
- (uint32_t)sub->entries[index]);
-
- if ( !sub->lengths[index] && sub->entries[index] )
- {
- _sub_table_print((dir_sub_table_t*)sub->entries[index], level+1, table);
- }
- }
-}
-
-/* Print a table.
- * Prints a table and its subtable. This is used for debugging purpose only.
- * @param table The table that describes all, returned by dir_new
- */
-void sfrt_dir_print(void* tbl)
-{
- dir_table_t* table = (dir_table_t*)tbl;
-
- if (!table)
- {
- return;
- }
-
- printf ("Nodes in use: %d\n", table->cur_num);
- if (table->sub_table)
- {
- _sub_table_print(table->sub_table, 1, table);
- }
-}
-
-/* Sub table removal
- * Recursive function to drill down to subnet table and remove entries.
- * @param ip IP address structure
- * @param length Number of bits of the IP used to specify this CIDR
- * @param cur_len Number of bits of the IP left at this depth
- * @param current_depth Number of levels down from root_table.
- * @param behavior RT_FAVOR_SPECIFIC or RT_FAVOR_TIME
- * @param root_table The table that describes all, returned by dir_new
- * @returns index of entry removed. Returns 0, which is a valid index, as failure code.
- * Calling function should treat 0 index as failure case.*/
-
-static int _dir_sub_remove(IPLOOKUP* ip, int length, int cur_len,
- int current_depth, int behavior,
- dir_sub_table_t* sub_table, dir_table_t* root_table)
-{
- word index;
- uint32_t valueIndex = 0;
-
- {
- uint32_t local_index, i;
- /* need to handle bits usage across multiple 32bit vals within IPv6. */
- if (ip->bits < 32)
- {
- i=0;
- }
- else if (ip->bits < 64)
- {
- i=1;
- }
- else if (ip->bits < 96)
- {
- i=2;
- }
- else
- {
- i=3;
- }
- local_index = ip->addr[i] << (ip->bits % 32);
- index = local_index >> (sizeof(local_index) * 8 - sub_table->width);
- }
-
- /* Check if this is the last table to traverse to */
- if (sub_table->width >= cur_len)
- {
- /* Calculate how many entries need to be removed (filled with 0)
- * in this table. If the table is 24 bits wide, and the entry
- * is 20 bytes long, 2^4 entries need to be filled. */
- uint32_t fill = 1 << (sub_table->width - cur_len);
-
- index = (index >> (sub_table->width - cur_len)) <<
- (sub_table->width - cur_len);
-
- fill += index;
-
- /* Remove and overwrite without considering CIDR specificity*/
- if (behavior == RT_FAVOR_TIME)
- {
- valueIndex = _dir_remove_all(&root_table->allocated, index, fill, length, sub_table);
- }
- /* Remove and overwrite only less specific CIDR */
- else
- {
- valueIndex = _dir_remove_less_specific(&root_table->allocated, index, fill, length,
- sub_table);
- }
- }
- else
- {
- /* traverse to a next sub-table down*/
-
- dir_sub_table_t* next_sub = (dir_sub_table_t*)sub_table->entries[index];
-
- /*subtable was never added. */
- if (!next_sub || sub_table->lengths[index])
- {
- return 0;
- }
- /* Recurse to next level. Rightshift off appropriate number of
- * bits and update the length accordingly. */
- ip->bits += sub_table->width;
- valueIndex = _dir_sub_remove(ip, length,
- cur_len - sub_table->width, current_depth+1,
- behavior, next_sub, root_table);
- if (!next_sub->filledEntries)
- {
- _sub_table_free(&root_table->allocated, next_sub);
- sub_table->entries[index] = 0;
- sub_table->lengths[index] = 0;
- sub_table->filledEntries--;
- root_table->cur_num--;
- }
- }
-
- return valueIndex;
-}
-
-/* Remove entry into DIR-n-m tables
- * @return index to data or 0 on failure. Calling function should check for 0 since
- * this is valid index for failed operation.
- */
-word sfrt_dir_remove(const uint32_t* addr, int /* numAddrDwords */, int len, int behavior, void* table)
-{
- dir_table_t* root = (dir_table_t*)table;
- uint32_t h_addr[4];
- IPLOOKUP iplu;
- iplu.addr = h_addr;
- iplu.bits = 0;
-
- /* Validate arguments */
- if (!root || !root->sub_table)
- {
- return 0;
- }
-
- h_addr[0] = ntohl(addr[0]);
- if (len > 96)
- {
- h_addr[1] = ntohl(addr[1]);
- h_addr[2] = ntohl(addr[2]);
- h_addr[3] = ntohl(addr[3]);
- }
- else if (len > 64)
- {
- h_addr[1] = ntohl(addr[1]);
- h_addr[2] = ntohl(addr[2]);
- h_addr[3] = 0;
- }
- else if (len > 32)
- {
- h_addr[1] = ntohl(addr[1]);
- h_addr[2] = 0;
- h_addr[3] = 0;
- }
- else
- {
- h_addr[1] = 0;
- h_addr[2] = 0;
- h_addr[3] = 0;
- }
-
- /* Find the sub table in which to remove */
- return _dir_sub_remove(&iplu, len, len, 0, behavior, root->sub_table, root);
-}
-
+++ /dev/null
-//--------------------------------------------------------------------------
-// Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
-// Copyright (C) 2006-2013 Sourcefire, Inc.
-//
-// 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. You may not use, modify or distribute
-// this program under any other version of the GNU General Public License.
-//
-// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
-//--------------------------------------------------------------------------
-
-/*
- * @file sfdir.h
- * @author Adam Keeton <akeeton@sourcefire.com>
- * @date Thu July 20 10:16:26 EDT 2006
- *
- */
-
-#ifndef SFRT_DIR_H
-#define SFRT_DIR_H
-
- // The implementation uses an multibit-trie that is similar to Gupta et-al's
- // DIR-n-m.
-
-#include <cstdint>
-
-/*******************************************************************/
-/* DIR-n-m data structures
- * Each table in the DIR-n-m method is represented by a
- * dir_sub_table_t. They are managed by a dir_table_t. */
-typedef struct
-{
- word* entries;
- uint8_t* lengths;
- int num_entries; /* Number of entries in this table */
- int width; /* width of this table. */
- /* While one determines the other, this way fewer
- * calculations are needed at runtime, since both
- * are used. */
- int cur_num; /* Present number of used nodes */
-
- /** number of entries filled including children sub_tables. This is used
- * for freeing sub_tables when all entries are freed by delete operation.
- */
- int filledEntries;
-} dir_sub_table_t;
-
-/* Master data structure for the DIR-n-m derivative */
-typedef struct
-{
- int* dimensions; /* DIR-n-m will consist of any number of arbitrarily
- * long tables. This variable keeps track of the
- * dimensions */
- int dim_size; /* And this variable keeps track of 'dimensions''s
- * dimensions! */
- uint32_t mem_cap; /* User-defined maximum memory that can be allocated
- * for the DIR-n-m derivative */
-
- int cur_num; /* Present number of used nodes */
-
- uint32_t allocated;
-
- dir_sub_table_t* sub_table;
-} dir_table_t;
-
-/******************************************************************
- DIR-n-m functions, these are not intended to be called directly */
-dir_table_t* sfrt_dir_new(uint32_t mem_cap, int count,...);
-void sfrt_dir_free(void*);
-tuple_t sfrt_dir_lookup(const uint32_t* addr, int numAddrDwords, void* table);
-int sfrt_dir_insert(const uint32_t* addr, int numAddrDwords, int len, word data_index,
- int behavior, void* table);
-uint32_t sfrt_dir_usage(void* table);
-void sfrt_dir_print(void* table);
-word sfrt_dir_remove(const uint32_t* addr, int numAddrDwords, int len, int behavior, void* table);
-
-#endif /* SFRT_DIR_H */
-
/* Allocate the user-specified DIR-n-m table */
switch (table_flat_type)
{
+#if 0
case DIR_24_8:
table->rt = sfrt_dir_flat_new(mem_cap, 2, 24, 8);
break;
table->rt = sfrt_dir_flat_new(mem_cap, 2, 16,16);
table->rt6 = sfrt_dir_flat_new(mem_cap, 8, 16,16,16,16,16,16,16,16);
break;
+#endif
case DIR_8x16:
table->rt = sfrt_dir_flat_new(mem_cap, 4, 16,8,4,4);
table->rt6 = sfrt_dir_flat_new(mem_cap, 16,
break;
}
- if ((!table->rt) || (!table->rt6))
- {
- if (table->rt)
- sfrt_dir_flat_free(table->rt);
- if (table->rt6)
- sfrt_dir_flat_free(table->rt6);
- segment_free(table->data);
- segment_free(table_ptr);
- return nullptr;
- }
+ assert(table->rt);
+ assert(table->rt6);
return table;
}
-/* Free lookup table */
-void sfrt_flat_free(TABLE_PTR table_ptr)
-{
- table_flat_t* table;
- uint8_t* base;
-
- if (!table_ptr)
- {
- /* What are you calling me for? */
- return;
- }
-
- base = (uint8_t*)segment_basePtr();
- table = (table_flat_t*)(&base[table_ptr]);
-
- if (!table->data)
- {
- /* This really really should not have happened */
- }
- else
- {
- segment_free(table->data);
- }
-
- if (!table->rt)
- {
- /* This should not have happened either */
- }
- else
- {
- sfrt_dir_flat_free(table->rt);
- }
-
- if (!table->rt6)
- {
- /* This should not have happened either */
- }
- else
- {
- sfrt_dir_flat_free(table->rt6);
- }
-
- segment_free(table_ptr);
-}
-
/* Perform a lookup on value contained in "ip" */
GENERIC sfrt_flat_lookup(const SfIp* ip, table_flat_t* table)
{
/* Abstracted routing table API */
table_flat_t* sfrt_flat_new(char table_flat_type, char ip_type,
long data_size, uint32_t mem_cap);
-void sfrt_flat_free(TABLE_PTR table);
GENERIC sfrt_flat_lookup(const snort::SfIp* ip, table_flat_t* table);
GENERIC sfrt_flat_dir8x_lookup(const snort::SfIp* ip, table_flat_t* table);
return table_ptr;
}
+#if 0
/* Traverse "sub" tables, freeing each */
static void _sub_table_flat_free(uint32_t* allocated, SUB_TABLE_PTR sub_ptr)
{
*allocated -= sizeof(dir_sub_table_flat_t);
}
-/* Free the DIR-n-m structure */
-void sfrt_dir_flat_free(TABLE_PTR tbl_ptr)
-{
- dir_table_flat_t* table;
- uint8_t* base;
-
- if (!tbl_ptr)
- {
- return;
- }
-
- base = (uint8_t*)segment_basePtr();
- table = (dir_table_flat_t*)(&base[tbl_ptr]);
-
- if (table->sub_table)
- {
- _sub_table_flat_free(&table->allocated, table->sub_table);
- }
-
- segment_free(tbl_ptr);
-}
-
static inline void _dir_fill_all(uint32_t* allocated, uint32_t index, uint32_t fill,
word length, uint32_t val, SUB_TABLE_PTR sub_ptr)
{
}
}
}
+#endif
static inline int64_t _dir_update_info(int index, int fill,
word length, uint32_t val, SUB_TABLE_PTR sub_ptr, updateEntryInfoFunc updateEntry, INFO* data)
fill += index;
+#if 0
/* Favor most recent CIDR */
if (behavior == RT_FAVOR_TIME)
{
_dir_fill_less_specific(index, fill, length, (word)ptr, sub_ptr);
}
else if (behavior == RT_FAVOR_ALL)
+#endif
+ assert(behavior == RT_FAVOR_ALL);
{
int64_t bytesAllocated;
/******************************************************************
DIR-n-m functions, these are not intended to be called directly */
TABLE_PTR sfrt_dir_flat_new(uint32_t mem_cap, int count,...);
-void sfrt_dir_flat_free(TABLE_PTR);
tuple_flat_t sfrt_dir_flat_lookup(const uint32_t* addr, int numAddrDwords, TABLE_PTR table);
int sfrt_dir_flat_insert(const uint32_t* addr, int numAddrDwords, int len, word data_index,
int behavior, TABLE_PTR, updateEntryInfoFunc updateEntry, INFO *data);
+++ /dev/null
-//--------------------------------------------------------------------------
-// Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
-// Copyright (C) 2009-2013 Sourcefire, Inc.
-//
-// 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. You may not use, modify or distribute
-// this program under any other version of the GNU General Public License.
-//
-// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
-//--------------------------------------------------------------------------
-// sfrt_test.cc author Hui Cao <hcao@sourcefire.com>
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include "catch/snort_catch.h"
-#include "sfip/sf_cidr.h"
-#include "utils/util.h"
-
-#include "sfrt.h"
-
-using namespace snort;
-
-#define NUM_IPS 32
-#define NUM_DATA 4
-
-typedef struct
-{
- const char* ip_str;
- int value;
-} IP_entry;
-
-static IP_entry ip_lists[] =
-{
-// __STRDUMP_DISABLE__
- { "192.168.0.1",4 },
- { "2.16.0.1", 100 },
- { "12.16.0.1", 500 },
- { "19.16.0.1", 12345 },
- { "12.16.0.2", 567890 },
- { "12.168.0.1", 456 },
- { "12.178.0.1", 123456 },
- { "192.168.0.11", 345667 },
- { "192.16.0.17/16", 345667 },
- { "192.168.0.12", 10 },
- { "::FFFF:129.144.52.38", 120 },
- { "ffee:ddcc:bbaa:9988:7766:5544:3322:1100/32", 121 },
- { "1001:db8:85a3::/29", 122 },
- { "255.255.255.255", 0 }
-// __STRDUMP_ENABLE__
-};
-
-//---------------------------------------------------------------
-
-static int s_debug = 0;
-
-/* Add one ip, then delete that IP*/
-static void test_sfrt_remove_after_insert()
-{
- table_t* dir;
- unsigned num_entries;
- unsigned index;
-
- num_entries = sizeof(ip_lists)/sizeof(ip_lists[0]);
- if ( s_debug )
- printf("Number of entries: %u \n",num_entries);
-
- dir = sfrt_new(DIR_16_4x4_16x5_4x4, IPv6, num_entries + 1, 200);
-
- CHECK(dir != nullptr); // "sfrt_new()"
-
- for (index=0; index<num_entries; index++)
- {
- SfCidr ip;
- SfIp ip2;
- int val;
- int* result = nullptr;
-
- IP_entry* ip_entry = &(ip_lists[index]);
-
- /*Parse IP*/
- ip.set(ip_entry->ip_str);
- char* ip2_str = snort_strdup(ip_entry->ip_str);
- char* p = strchr(ip2_str, '/');
- if (p)
- *p = '\0';
- ip2.set(ip2_str);
- snort_free(ip2_str);
-
- if ( s_debug )
- {
- SfIpString ip_str;
- printf("Insert IP addr: %s, family: %d\n", ip.get_addr()->ntop(ip_str), ip.get_family());
- }
- CHECK(sfrt_insert(&ip, ip.get_bits(), &(ip_entry->value), RT_FAVOR_TIME, dir) ==
- RT_SUCCESS); // "sfrt_insert()"
-
- if ( s_debug )
- {
- SfIpString ip_str;
- printf("Lookup IP addr: %s, family: %d\n", ip2.ntop(ip_str), ip2.get_family());
- }
- result = (int*)sfrt_lookup(&ip2, dir);
- if ( s_debug )
- {
- if (result)
- printf("value input: %d, output: %d\n", ip_entry->value, *result);
- else
- printf("value input: %d, output: nullptr\n", ip_entry->value);
- }
-
- CHECK(result != nullptr); // "sfrt_lookup()"
-
- if ( s_debug )
- {
- SfIpString ip_str;
- printf("IP addr: %s, family: %d\n", ip.get_addr()->ntop(ip_str), ip.get_family());
- printf("value input: %d, output: %d\n", ip_entry->value, *result);
- }
-
- CHECK(sfrt_remove(&ip, ip.get_bits(), (void**)&result, RT_FAVOR_TIME, dir) == RT_SUCCESS);
- CHECK(result != nullptr); //sfrt_remove()"
-
- val = *result;
- if ( s_debug )
- printf("value expected: %d, actual: %d\n", ip_entry->value, val);
-
- CHECK(val == ip_entry->value); //sfrt_remove(): value return"
- CHECK(sfrt_lookup(ip.get_addr(), dir) == nullptr); // "sfrt_lookup(): value return"
- }
-
- if ( s_debug )
- {
- printf("Usage: %u bytes\n", sfrt_usage(dir));
- printf("Number of entries: %u \n", sfrt_num_entries(dir));
- }
-
- sfrt_free(dir);
-}
-
-/*Add all IPs, then delete all of them*/
-static void test_sfrt_remove_after_insert_all()
-{
- table_t* dir;
- unsigned num_entries;
- unsigned index;
-
- num_entries = sizeof(ip_lists)/sizeof(ip_lists[0]);
-
- if ( s_debug )
- printf("Number of entries: %u \n",num_entries);
-
- dir = sfrt_new(DIR_16_4x4_16x5_4x4, IPv6, num_entries + 1, 200);
-
- CHECK(dir != nullptr); // "sfrt_new()"
-
- /*insert all entries*/
- for (index=0; index<num_entries; index++)
- {
- SfCidr ip;
- SfIp ip2;
- int* result;
-
- IP_entry* ip_entry = &(ip_lists[index]);
- /*Parse IP*/
- ip.set(ip_entry->ip_str);
- char* ip2_str = snort_strdup(ip_entry->ip_str);
- char* p = strchr(ip2_str, '/');
- if (p)
- *p = '\0';
- ip2.set(ip2_str);
- snort_free(ip2_str);
-
- CHECK(sfrt_insert(&ip, ip.get_bits(), &(ip_entry->value), RT_FAVOR_TIME, dir) ==
- RT_SUCCESS); // "sfrt_insert()"
-
- result = (int*)sfrt_lookup(ip.get_addr(), dir);
-
- if ( s_debug )
- printf("value input: %d, output: %d\n", ip_entry->value, result ? *result : -1);
-
- CHECK(result != nullptr); // "sfrt_lookup()"
- }
-
- if ( s_debug )
- {
- printf("Usage: %u bytes\n", sfrt_usage(dir));
- printf("Number of entries: %u \n", sfrt_num_entries(dir));
- }
-
- /*remove all entries*/
- for (index=0; index<num_entries; index++)
- {
- SfCidr ip;
- int val;
- int* result = nullptr;
-
- IP_entry* ip_entry = &(ip_lists[index]);
- /*Parse IP*/
- ip.set(ip_entry->ip_str);
-
- CHECK(sfrt_remove(&ip, ip.get_bits(), (void**)&result, RT_FAVOR_TIME, dir) == RT_SUCCESS);
-
- REQUIRE(result != nullptr);
-
- val = *result;
- if ( s_debug )
- printf("value expected: %d, actual: %d\n", ip_entry->value, val);
-
- CHECK(val == ip_entry->value); //sfrt_remove(): value return"
- CHECK(!sfrt_lookup(ip.get_addr(), dir));
-
- /*check the next entry still exist*/
- if (index + 1 < num_entries)
- {
- ip_entry = &(ip_lists[index + 1]);
- /*Parse IP*/
- ip.set(ip_entry->ip_str);
- CHECK(sfrt_lookup(ip.get_addr(), dir)); // "sfrt_lookup(): value return"
- }
- }
-
- if ( s_debug )
- {
- printf("Usage: %u bytes\n", sfrt_usage(dir));
- printf("Number of entries: %u \n", sfrt_num_entries(dir));
- }
-
- sfrt_free(dir);
-}
-
-TEST_CASE("sfrt", "[sfrt]")
-{
- SECTION("remove after insert")
- {
- test_sfrt_remove_after_insert();
- }
- SECTION("remove after insert all")
- {
- test_sfrt_remove_after_insert_all();
- }
-}
-
config->ports = new PortBitSet;
v.get_bits(*(config->ports) );
}
- else
- return false;
return true;
}
if ( v.is("idle_timeout") )
config.flow_cache_cfg.proto[to_utype(type)].nominal_timeout = v.get_uint32();
+
else if ( v.is("cap_weight") )
config.flow_cache_cfg.proto[to_utype(type)].cap_weight = v.get_uint16();
bool StreamFileModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("upload") )
- upload = v.get_bool();
-
- else
- return false;
-
+ assert(v.is("upload"));
+ upload = v.get_bool();
return true;
}
bool StreamIcmpModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("session_timeout") )
- config->session_timeout = v.get_uint32();
-
- else
- return false;
-
+ assert(v.is("session_timeout"));
+ config->session_timeout = v.get_uint32();
return true;
}
else if ( v.is("fastpath") )
srod.fastpath = 1;
- else
- return false;
-
return true;
}
else if ( v.is("~direction") )
direction = v.get_uint8();
- else
- return false;
-
return true;
}
else
config->flags &= ~STREAM_CONFIG_NO_REASSEMBLY;
}
- else
- return false;
return true;
}
return true;
}
-#if 0 // FIXIT-M unit tests need work
-#include "tcp_normalizers.h"
-#include "tcp_reassemblers.h"
-
-TEST_CASE("TCP State Closed", "[tcp_closed_state][stream_tcp]")
-{
- // initialization code here
- Flow* flow = new Flow;
- TcpStreamTracker* ctrk = new TcpStreamTracker(true);
- TcpStreamTracker* strk = new TcpStreamTracker(false);
- TcpEventLogger* tel = new TcpEventLogger;
- TcpSession* session = new TcpSession(flow);
- TcpStateMachine* tsm = new TcpStateMachine;
- TcpStateHandler* tsh = new TcpStateClosed(*tsm, *session);
- ctrk->normalizer = TcpNormalizerFactory::create(StreamPolicy::OS_LINUX, session, ctrk, strk);
- strk->normalizer = TcpNormalizerFactory::create(StreamPolicy::OS_LINUX, session, strk, ctrk);
- ctrk->reassembler = TcpReassemblerFactory::create(session, ctrk, StreamPolicy::OS_LINUX,
- false);
- strk->reassembler = TcpReassemblerFactory::create(session, strk, StreamPolicy::OS_LINUX, true);
-
- SECTION("syn_packet")
- {
- Packet* pkt = get_syn_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("syn_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK(TcpStreamTracker::TCP_SYN_SENT_EVENT == ctrk->get_tcp_event() );
- //CHECK( ( ctrk->get_iss() == 9050 ) );
- //CHECK( ( ctrk->get_snd_una() == 9051 ) );
- //CHECK( ( ctrk->get_snd_nxt() == 9050 ) );
- //CHECK( ( ctrk->get_snd_wnd() == 8192 ) );
- }
-
- SECTION("syn_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("syn_ack_packet")
- {
- Packet* pkt = get_syn_ack_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("syn_ack_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("syn_ack_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("ack_packet")
- {
- Packet* pkt = get_ack_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("ack_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("ack_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("data_seg_packet")
- {
- Packet* pkt = get_data_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("data_seg_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("data_seg_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("fin_packet")
- {
- Packet* pkt = get_fin_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("fin_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("fin_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("rst_packet")
- {
- Packet* pkt = get_rst_packet(flow);
- REQUIRE( ( pkt != nullptr ));
-
- SECTION("rst_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ));
- }
-
- SECTION("rst_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- delete flow;
- delete tsh;
- delete ctrk;
- delete strk;
-}
-
-#endif
-
return false;
}
-// FIXIT-RC get the unit test working again
-#ifdef UNIT_TEST_FOO
-
-SCENARIO("TCP State Handler Base Class", "[state_handlers][stream_tcp]")
-{
- // initialization code here
- Flow* flow = new Flow;
- TcpStateHandler* tsh = new TcpStateHandler;
- TcpStreamTracker* client_tracker = new TcpStreamTracker(true);
- TcpStreamTracker* server_tracker = new TcpStreamTracker(false);
- TcpEventLogger tel;
-
- GIVEN("a SYN Packet")
- {
- Packet* pkt = get_syn_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- WHEN("SYN is sent")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- client_tracker->set_tcp_event(TcpStreamTracker::TCP_SYN_SENT_EVENT);
- tsh->eval(*tsd, *client_tracker);
- THEN("Event should be TCP_SYN_SENT_EVENT")
- {
- CHECK( ( tsh->get_tcp_event() == client_tracker->get_tcp_event() ) );
- }
- delete tsd;
- }
-
- SECTION("SYN is received")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- server_tracker->set_tcp_event(TcpStreamTracker::TCP_SYN_RECV_EVENT);
- tsh->eval(*tsd, *server_tracker);
- CHECK( ( tsh->get_tcp_event() == server_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- delete pkt;
- }
-
- SECTION("syn_ack_packet")
- {
- Packet* pkt = get_syn_ack_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("syn_ack_sent")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- client_tracker->set_tcp_event(TcpStreamTracker::TCP_SYN_ACK_SENT_EVENT);
- tsh->eval(*tsd, *client_tracker);
- CHECK( ( tsh->get_tcp_event() == client_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- SECTION("syn_ack_recv")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- server_tracker->set_tcp_event(TcpStreamTracker::TCP_SYN_ACK_RECV_EVENT);
- tsh->eval(*tsd, *server_tracker);
- CHECK( ( tsh->get_tcp_event() == server_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- delete pkt;
- }
-
- SECTION("ack_packet")
- {
- Packet* pkt = get_ack_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("ack_sent")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- client_tracker->set_tcp_event(TcpStreamTracker::TCP_ACK_SENT_EVENT);
- tsh->eval(*tsd, *client_tracker);
- CHECK( ( tsh->get_tcp_event() == client_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- SECTION("ack_recv")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- server_tracker->set_tcp_event(TcpStreamTracker::TCP_ACK_RECV_EVENT);
- tsh->eval(*tsd, *server_tracker);
- CHECK( ( tsh->get_tcp_event() == server_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- delete pkt;
- }
-
- SECTION("data_seg_packet")
- {
- Packet* pkt = get_data_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("data_seg_sent")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- client_tracker->set_tcp_event(TcpStreamTracker::TCP_DATA_SEG_SENT_EVENT);
- tsh->eval(*tsd, *client_tracker);
- CHECK( ( tsh->get_tcp_event() == client_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- SECTION("data_seg_recv")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- server_tracker->set_tcp_event(TcpStreamTracker::TCP_DATA_SEG_RECV_EVENT);
- tsh->eval(*tsd, *server_tracker);
- CHECK( ( tsh->get_tcp_event() == server_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- delete pkt;
- }
-
- SECTION("fin_packet")
- {
- Packet* pkt = get_fin_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("fin_sent")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- client_tracker->set_tcp_event(TcpStreamTracker::TCP_FIN_SENT_EVENT);
- tsh->eval(*tsd, *client_tracker);
- CHECK( ( tsh->get_tcp_event() == client_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- SECTION("fin_recv")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- server_tracker->set_tcp_event(TcpStreamTracker::TCP_FIN_RECV_EVENT);
- tsh->eval(*tsd, *server_tracker);
- CHECK( ( tsh->get_tcp_event() == server_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- delete pkt;
- }
-
- SECTION("rst_packet")
- {
- Packet* pkt = get_rst_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("rst_sent")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- client_tracker->set_tcp_event(TcpStreamTracker::TCP_RST_SENT_EVENT);
- tsh->eval(*tsd, *client_tracker);
- CHECK( ( tsh->get_tcp_event() == client_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- SECTION("rst_recv")
- {
- TcpSegmentDescriptor* tsd = new TcpSegmentDescriptor(flow, pkt, tel);
- server_tracker->set_tcp_event(TcpStreamTracker::TCP_RST_RECV_EVENT);
- tsh->eval(*tsd, *server_tracker);
- CHECK( ( tsh->get_tcp_event() == server_tracker->get_tcp_event() ) );
- delete tsd;
- }
-
- delete pkt;
- }
-
- delete flow;
- delete tsh;
- delete client_tracker;
- delete server_tracker;
-}
-
-#endif
-
return true;
}
-#if 0 // FIXIT-M unit tests need work
-#include "tcp_normalizers.h"
-#include "tcp_reassemblers.h"
-
-TEST_CASE("TCP State None", "[tcp_none_state][stream_tcp]")
-{
- // initialization code here
- Flow* flow = new Flow;
- TcpStreamTracker* ctrk = new TcpStreamTracker(true);
- TcpStreamTracker* strk = new TcpStreamTracker(false);
- TcpEventLogger* tel = new TcpEventLogger;
- TcpSession* session = new TcpSession(flow);
- TcpStateMachine* tsm = new TcpStateMachine;
- TcpStateHandler* tsh = new TcpStateNone(*tsm, *session);
-
- ctrk->normalizer = TcpNormalizerFactory::create(StreamPolicy::OS_LINUX, session, ctrk, strk);
- strk->normalizer = TcpNormalizerFactory::create(StreamPolicy::OS_LINUX, session, strk, ctrk);
- ctrk->reassembler = TcpReassemblerFactory::create(session, ctrk, StreamPolicy::OS_LINUX,
- false);
- strk->reassembler = TcpReassemblerFactory::create(session, strk, StreamPolicy::OS_LINUX, true);
-
- SECTION("syn_packet")
- {
- Packet* pkt = get_syn_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("syn_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK(TcpStreamTracker::TCP_SYN_SENT_EVENT == ctrk->get_tcp_event() );
- //CHECK( ( ctrk->get_iss() == 9050 ) );
- //CHECK( ( ctrk->get_snd_una() == 9051 ) );
- //CHECK( ( ctrk->get_snd_nxt() == 9050 ) );
- //CHECK( ( ctrk->get_snd_wnd() == 8192 ) );
- }
-
- SECTION("syn_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("syn_ack_packet")
- {
- Packet* pkt = get_syn_ack_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("syn_ack_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("syn_ack_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("ack_packet")
- {
- Packet* pkt = get_ack_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("ack_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("ack_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("data_seg_packet")
- {
- Packet* pkt = get_data_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("data_seg_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("data_seg_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("fin_packet")
- {
- Packet* pkt = get_fin_packet(flow);
- REQUIRE( ( pkt != nullptr ) );
-
- SECTION("fin_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- SECTION("fin_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- SECTION("rst_packet")
- {
- Packet* pkt = get_rst_packet(flow);
- REQUIRE( ( pkt != nullptr ));
-
- SECTION("rst_sent")
- {
- flow->ssn_state.direction = FROM_CLIENT;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ));
- }
-
- SECTION("rst_recv")
- {
- flow->ssn_state.direction = FROM_SERVER;
- TcpSegmentDescriptor tsd(flow, pkt, tel);
- ctrk->set_tcp_event(tsd);
- ctrk->set_require_3whs(false);
- tsh->eval(tsd, *ctrk);
- CHECK( ( tsh->get_tcp_event() == ctrk->get_tcp_event() ) );
- }
-
- delete pkt;
- }
-
- delete flow;
- delete tsh;
- delete ctrk;
- delete strk;
-}
-
-#endif
-
return pkt;
}
-Packet* get_ack_packet(Flow* flow)
-{
- Packet* pkt = init_packet(flow, PKT_FROM_CLIENT);
-
- pkt->pkt = cooked_ack;
- pkt->ptrs.tcph = ( const tcp::TCPHdr* )( cooked_ack + 34 );
-
- return pkt;
-}
-
-Packet* get_fin_packet(Flow* flow)
-{
- Packet* pkt = init_packet(flow, PKT_FROM_CLIENT);
-
- pkt->pkt = cooked_fin;
- pkt->ptrs.tcph = ( const tcp::TCPHdr* )( cooked_fin + 34 );
-
- return pkt;
-}
-
-Packet* get_rst_packet(Flow* flow)
-{
- Packet* pkt = init_packet(flow, PKT_FROM_CLIENT);
-
- pkt->pkt = cooked_rst;
- pkt->ptrs.tcph = ( const tcp::TCPHdr* )( cooked_rst + 34 );
-
- return pkt;
-}
-
-Packet* get_data_packet(Flow* flow)
-{
- Packet* pkt = init_packet(flow, PKT_FROM_CLIENT);
-
- pkt->pkt = cooked_data;
- pkt->ptrs.tcph = ( const tcp::TCPHdr* )( cooked_data + 34 );
- pkt->dsize = 42;
-
- return pkt;
-}
-
bool StreamUdpModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("session_timeout") )
- config->session_timeout = v.get_uint32();
-
- else
- return false;
-
+ assert(v.is("session_timeout"));
+ config->session_timeout = v.get_uint32();
return true;
}
#include "config.h"
#endif
+#include <cassert>
+
#include "stream_user.h"
#include "log/messages.h"
void StreamUser::show(const SnortConfig*) const
{
- if ( !config )
- return;
-
+ assert(config);
ConfigLogger::log_value("session_timeout", config->session_timeout);
}
};
StreamUserModule::StreamUserModule() : Module(MOD_NAME, MOD_HELP, s_params)
-{
- config = nullptr;
-}
+{ config = nullptr; }
StreamUserModule::~StreamUserModule()
-{
- if ( config )
- delete config;
-}
+{ delete config; }
StreamUserConfig* StreamUserModule::get_data()
{
bool StreamUserModule::set(const char*, Value& v, SnortConfig*)
{
- if ( v.is("session_timeout") )
- config->session_timeout = v.get_uint32();
-
+ assert(v.is("session_timeout"));
+ config->session_timeout = v.get_uint32();
return true;
}
snort::StreamSplitter* get_splitter(bool c2s) override;
void restart(snort::Packet*) override;
- bool is_sequenced(uint8_t /*dir*/) override
- { return true; }
-
- bool are_packets_missing(uint8_t /*dir*/) override
- { return false; }
-
- uint8_t missing_in_reassembled(uint8_t /*dir*/) override
- { return SSN_MISSING_NONE; }
-
private:
void start(snort::Packet*, snort::Flow*);
void update(snort::Packet*, snort::Flow*);
int update_alert(
snort::Packet*, uint32_t gid, uint32_t sid, uint32_t event_id, uint32_t event_second) override;
- void flush_client(snort::Packet*) override { }
- void flush_server(snort::Packet*) override { }
- void flush_talker(snort::Packet*, bool /*final_flush */ = false) override { }
- void flush_listener(snort::Packet*, bool /*final_flush */ = false) override { }
-
- void set_extra_data(snort::Packet*, uint32_t /* flag */) override { }
-
uint8_t get_reassembly_direction() override;
public:
%option c++
%option batch
-
%option never-interactive
+%option noinput nounput
+%option noyy_push_state noyy_pop_state noyy_top_state
%{
#include "utils/js_identifier_ctx.h"
#include "utils/util_cstring.h"
+#define YY_NO_UNPUT
#define YY_USER_ACTION \
{ \
debug_logf(5, http_trace, TRACE_JS_PROC, nullptr, \