From 587470f8d4b6e3ff704a4bb5f6c3c58a4e84da22 Mon Sep 17 00:00:00 2001 From: "Michael Altizer (mialtize)" Date: Tue, 6 Dec 2016 17:39:14 -0500 Subject: [PATCH] Merge pull request #731 in SNORT/snort3 from sfip to master Squashed commit of the following: commit 7d6beaa500576fd94654482baea2841c626094ea Author: Michael Altizer Date: Mon Oct 17 21:39:28 2016 -0400 sfip: Refactoring and split from SfCidr commit 0910494ac22e82569b8faf2b041828b31708f5d7 Author: Michael Altizer Date: Thu Oct 20 13:16:00 2016 -0400 sf_vartable: Initial conversion to Catch unit tests commit 17c20f297605fbe954c26e0d2061fa258af7bf49 Author: Michael Altizer Date: Wed Nov 30 14:07:25 2016 -0500 main: Mark main_read() as static commit 30c7b6fd9413f0f338cd22f37dc37e79657054b5 Author: Michael Altizer Date: Wed Nov 23 12:04:42 2016 -0500 appid: Remove unused API HTTP field functions --- extra/src/inspectors/data_log/data_log.cc | 6 +- extra/src/inspectors/http_server/hi_client.cc | 21 +- extra/src/inspectors/http_server/hi_main.cc | 10 +- extra/src/inspectors/http_server/hi_main.h | 2 +- extra/src/inspectors/http_server/hi_si.cc | 13 +- extra/src/inspectors/http_server/hi_si.h | 6 +- src/actions/act_react.cc | 1 + src/codecs/ip/cd_icmp4.cc | 20 +- src/codecs/ip/cd_icmp6.cc | 9 +- src/codecs/ip/cd_ipv6.cc | 18 +- src/codecs/ip/cd_tcp.cc | 1 + src/codecs/ip/cd_udp.cc | 1 + src/codecs/misc/cd_user.cc | 12 +- src/detection/detect.cc | 4 +- src/detection/fp_detect.cc | 4 +- src/detection/service_map.cc | 1 + src/detection/tag.cc | 36 +- src/file_api/circular_buffer.cc | 4 - src/file_api/file_api.h | 1 - src/file_api/file_cache.cc | 6 +- src/file_api/file_cache.h | 21 +- src/file_api/file_capture.cc | 1 + src/file_api/file_capture.h | 5 +- src/file_api/file_config.cc | 6 +- src/file_api/file_config.h | 1 - src/file_api/file_enforcer.cc | 28 +- src/file_api/file_enforcer.h | 34 +- src/file_api/file_flows.cc | 21 +- src/file_api/file_flows.h | 5 +- src/file_api/file_identifier.cc | 5 +- src/file_api/file_identifier.h | 5 +- src/file_api/file_lib.cc | 16 +- src/file_api/file_lib.h | 10 +- src/file_api/file_log.cc | 28 +- src/file_api/file_mempool.cc | 4 - src/file_api/file_mempool.h | 2 +- src/file_api/file_module.cc | 1 + src/file_api/file_module.h | 4 +- src/file_api/file_policy.cc | 6 +- src/file_api/file_segment.cc | 4 +- src/file_api/file_segment.h | 6 +- src/file_api/file_service.cc | 21 +- src/file_api/file_service.h | 3 +- src/file_api/file_stats.cc | 15 +- src/file_api/file_stats.h | 10 +- src/filters/detection_filter.cc | 2 +- src/filters/detection_filter.h | 4 +- src/filters/rate_filter.cc | 19 +- src/filters/sfrf.cc | 42 +- src/filters/sfrf.h | 6 +- src/filters/sfrf_test.cc | 6 +- src/filters/sfthd.cc | 28 +- src/filters/sfthd.h | 21 +- src/filters/sfthd_test.cc | 8 +- src/filters/sfthreshold.cc | 2 +- src/filters/sfthreshold.h | 4 +- src/flow/expect_cache.cc | 8 +- src/flow/expect_cache.h | 5 +- src/flow/flow.cc | 8 +- src/flow/flow.h | 6 +- src/flow/flow_control.cc | 41 +- src/flow/flow_control.h | 10 +- src/flow/flow_key.cc | 61 +- src/flow/flow_key.h | 19 +- src/flow/ha.cc | 32 +- src/flow/session.h | 4 +- src/framework/value.cc | 21 +- src/framework/value.h | 6 +- src/hash/sfhashfcn.cc | 4 +- src/host_tracker/host_cache.cc | 7 +- src/host_tracker/host_cache.h | 2 +- src/host_tracker/host_tracker.h | 10 +- src/host_tracker/host_tracker_module.cc | 2 +- src/host_tracker/test/CMakeLists.txt | 4 +- src/host_tracker/test/Makefile.am | 4 +- .../test/host_cache_module_test.cc | 2 +- src/host_tracker/test/host_cache_test.cc | 29 +- .../test/host_tracker_module_test.cc | 10 +- src/host_tracker/test/host_tracker_test.cc | 13 +- src/ips_options/ips_byte_extract.cc | 1 + src/ips_options/ips_detection_filter.cc | 16 +- src/ips_options/ips_metadata.cc | 12 +- src/ips_options/ips_reference.cc | 8 +- src/ips_options/ips_sd_pattern.cc | 2 + src/ips_options/ips_session.cc | 20 +- src/ips_options/test/Makefile.am | 1 + src/latency/rule_latency.cc | 1 + src/log/log.cc | 1 + src/log/log_text.cc | 48 +- src/log/log_text.h | 2 - src/log/messages.cc | 21 +- src/log/messages.h | 4 +- src/loggers/alert_csv.cc | 8 +- src/loggers/alert_sf_socket.cc | 5 +- src/loggers/log_hext.cc | 2 +- src/loggers/unified2.cc | 12 +- src/main.cc | 2 +- src/main/modules.cc | 2 +- src/main/snort_config.cc | 14 +- src/main/snort_config.h | 18 +- src/main/thread.cc | 2 + src/managers/connector_manager.cc | 3 + src/network_inspectors/appid/app_forecast.cc | 4 +- src/network_inspectors/appid/appid_api.cc | 22 +- src/network_inspectors/appid/appid_api.h | 10 +- src/network_inspectors/appid/appid_config.h | 4 +- .../appid/appid_inspector.cc | 2 +- src/network_inspectors/appid/appid_module.cc | 4 +- src/network_inspectors/appid/appid_session.cc | 65 +- src/network_inspectors/appid/appid_session.h | 12 +- .../appid/appid_utils/ip_funcs.h | 9 +- .../appid/detector_plugins/detector_sip.cc | 10 +- .../appid/host_port_app_cache.cc | 20 +- .../appid/host_port_app_cache.h | 7 +- .../appid/lua_detector_api.cc | 24 +- .../appid/lua_detector_flow_api.cc | 12 +- .../appid/service_plugins/service_base.cc | 32 +- .../appid/service_plugins/service_ftp.cc | 34 +- .../appid/service_plugins/service_rexec.cc | 4 +- .../appid/service_plugins/service_rpc.cc | 4 +- .../appid/service_plugins/service_rshell.cc | 4 +- .../appid/service_plugins/service_snmp.cc | 4 +- .../appid/service_plugins/service_ssl.cc | 4 +- .../appid/service_plugins/service_tftp.cc | 4 +- src/network_inspectors/appid/service_state.cc | 27 +- src/network_inspectors/appid/service_state.h | 13 +- .../appid/test/appid_http_event_test.cc | 2 +- src/network_inspectors/arp_spoof/arp_spoof.cc | 6 +- .../binder/test/binder_test.cc | 6 +- .../packet_capture/packet_capture.cc | 1 + .../perf_monitor/flow_ip_tracker.cc | 30 +- .../perf_monitor/flow_ip_tracker.h | 4 +- src/network_inspectors/port_scan/ipobj.cc | 16 +- src/network_inspectors/port_scan/ipobj.h | 8 +- src/network_inspectors/port_scan/port_scan.cc | 34 +- src/network_inspectors/port_scan/ps_detect.cc | 63 +- src/network_inspectors/port_scan/ps_detect.h | 8 +- src/network_inspectors/port_scan/ps_inspect.h | 8 +- .../reputation/reputation_inspect.cc | 10 +- .../reputation/reputation_parse.cc | 63 +- src/packet_io/intf.cc | 7 +- src/packet_io/sfdaq.cc | 17 +- src/packet_io/sfdaq.h | 6 +- src/packet_io/trough.cc | 2 + src/parser/config_file.cc | 2 +- src/parser/vars.cc | 2 +- src/protocols/ip.cc | 26 +- src/protocols/ip.h | 14 +- src/protocols/ipv6.h | 1 - src/pub_sub/sip_events.cc | 2 +- src/pub_sub/sip_events.h | 2 +- src/service_inspectors/dce_rpc/dce_smb2.cc | 1 + .../dce_rpc/dce_smb_module.cc | 1 + .../ftp_telnet/ftp_bounce_lookup.cc | 10 +- .../ftp_telnet/ftp_bounce_lookup.h | 4 +- .../ftp_telnet/ftp_parse.cc | 2 +- .../ftp_telnet/ftp_print.cc | 2 +- src/service_inspectors/ftp_telnet/ftpp_si.cc | 8 +- src/service_inspectors/ftp_telnet/ftpp_si.h | 8 +- .../ftp_telnet/ftpp_ui_config.h | 4 +- src/service_inspectors/ftp_telnet/pp_ftp.cc | 55 +- src/service_inspectors/sip/sip_common.h | 4 +- src/service_inspectors/sip/sip_dialog.cc | 9 +- src/service_inspectors/sip/sip_parser.cc | 20 +- src/service_inspectors/smtp/smtp.cc | 1 + src/service_inspectors/smtp/smtp_module.cc | 1 + src/sfip/CMakeLists.txt | 5 +- src/sfip/Makefile.am | 5 +- src/sfip/sf_cidr.cc | 69 ++ src/sfip/sf_cidr.h | 166 ++++ src/sfip/sf_ip.cc | 396 +++------ src/sfip/sf_ip.h | 834 ++++++------------ src/sfip/sf_ipvar.cc | 122 ++- src/sfip/sf_ipvar.h | 21 +- src/sfip/sf_returns.h | 2 +- src/sfip/sf_vartable.cc | 102 +-- src/sfip/sf_vartable.h | 7 +- src/sfip/sfip_t.h | 85 -- src/sfip/sfip_test.cc | 246 ++---- src/sfrt/dev_notes.txt | 6 +- src/sfrt/sfrt.cc | 173 ++-- src/sfrt/sfrt.h | 102 +-- src/sfrt/sfrt_dir.cc | 241 ++--- src/sfrt/sfrt_dir.h | 6 +- src/sfrt/sfrt_flat.cc | 82 +- src/sfrt/sfrt_flat.h | 6 +- src/sfrt/sfrt_flat_dir.cc | 124 +-- src/sfrt/sfrt_flat_dir.h | 6 +- src/sfrt/sfrt_test.cc | 46 +- src/stream/base/stream_ha.cc | 12 +- src/stream/icmp/icmp_session.cc | 26 +- src/stream/icmp/icmp_session.h | 2 +- src/stream/ip/ip_defrag.cc | 1 + src/stream/libtcp/tcp_stream_session.cc | 14 +- src/stream/libtcp/tcp_stream_session.h | 2 +- src/stream/stream.cc | 18 +- src/stream/stream.h | 16 +- src/stream/tcp/tcp_session.cc | 6 +- src/stream/tcp/test/tcp_normalizer_test.cc | 2 +- src/stream/udp/udp_session.cc | 8 +- src/stream/udp/udp_session.h | 2 +- src/stream/user/user_session.cc | 4 +- src/stream/user/user_session.h | 2 +- src/target_based/sftarget_data.h | 4 +- src/target_based/sftarget_reader.cc | 21 +- src/target_based/sftarget_reader.h | 4 +- src/utils/util.cc | 2 + src/utils/util_net.cc | 24 +- src/utils/util_net.h | 4 +- 209 files changed, 2122 insertions(+), 2802 deletions(-) create mode 100644 src/sfip/sf_cidr.cc create mode 100644 src/sfip/sf_cidr.h delete mode 100644 src/sfip/sfip_t.h diff --git a/extra/src/inspectors/data_log/data_log.cc b/extra/src/inspectors/data_log/data_log.cc index 3e645ec29..c2c605f5a 100644 --- a/extra/src/inspectors/data_log/data_log.cc +++ b/extra/src/inspectors/data_log/data_log.cc @@ -38,7 +38,7 @@ #include "profiler/profiler.h" #include "utils/stats.h" #include "flow/flow.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" static const char* s_name = "data_log"; static const char* f_name = "data.log"; @@ -87,8 +87,8 @@ void LogHandler::handle(DataEvent& e, Flow* f) std::string val(b, n); TextLog_Print(tlog, "%u, ", time(nullptr)); - TextLog_Print(tlog, "%s, %d, ", sfip_to_str(&f->client_ip), f->client_port); - TextLog_Print(tlog, "%s, %d, ", sfip_to_str(&f->server_ip), f->server_port); + TextLog_Print(tlog, "%s, %d, ", f->client_ip.ntoa(), f->client_port); + TextLog_Print(tlog, "%s, %d, ", f->server_ip.ntoa(), f->server_port); TextLog_Print(tlog, "%s, %*s\n", key.c_str(), n, val.c_str()); dl_stats.total_packets++; diff --git a/extra/src/inspectors/http_server/hi_client.cc b/extra/src/inspectors/http_server/hi_client.cc index 004f54229..184e933ae 100644 --- a/extra/src/inspectors/http_server/hi_client.cc +++ b/extra/src/inspectors/http_server/hi_client.cc @@ -1018,15 +1018,15 @@ static const u_char* extract_http_xff(HI_SESSION* session, const u_char* p, cons const u_char* end, HI_CLIENT_HDR_ARGS* hdrs_args) { int num_spaces = 0; - SFIP_RET status; - sfip_t* tmp; + SfIpRet status; + SfIp* tmp; char* ipAddr = NULL; uint8_t unfold_buf[DECODE_BLEN]; uint32_t unfold_size =0; const u_char* start_ptr, * end_ptr, * cur_ptr; const u_char* port; HEADER_PTR* header_ptr; - sfip_t** true_ip; + SfIp** true_ip; header_ptr = hdrs_args->hdr_ptr; true_ip = &(hdrs_args->sd->true_ip); @@ -1082,7 +1082,8 @@ static const u_char* extract_http_xff(HI_SESSION* session, const u_char* p, cons } if (ipAddr) { - if ( (tmp = sfip_alloc(ipAddr, &status)) == NULL ) + tmp = new SfIp(); + if ((status = tmp->set(ipAddr)) != SFIP_SUCCESS) { port = (u_char*)SnortStrnStr((const char*)start_ptr, (cur_ptr - start_ptr), ":"); if (port) @@ -1090,11 +1091,12 @@ static const u_char* extract_http_xff(HI_SESSION* session, const u_char* p, cons snort_free(ipAddr); ipAddr = snort_strndup((const char*)start_ptr, port - start_ptr); - if ( (tmp = sfip_alloc(ipAddr, &status)) == NULL ) + if ((status = tmp->set(ipAddr)) != SFIP_SUCCESS) { if ((status != SFIP_ARG_ERR) && (status !=SFIP_ALLOC_ERR)) { hi_set_event(GID_HTTP_CLIENT, HI_CLIENT_INVALID_TRUEIP); + delete tmp; return p; } } @@ -1103,6 +1105,7 @@ static const u_char* extract_http_xff(HI_SESSION* session, const u_char* p, cons { hi_set_event(GID_HTTP_CLIENT, HI_CLIENT_INVALID_TRUEIP); snort_free(ipAddr); + delete tmp; return p; } } @@ -1114,7 +1117,7 @@ static const u_char* extract_http_xff(HI_SESSION* session, const u_char* p, cons if ( (hdrs_args->top_precedence > 0) && (hdrs_args->new_precedence >= hdrs_args->top_precedence) ) { - sfip_free(tmp); + delete tmp; snort_free(ipAddr); return( p ); } @@ -1131,16 +1134,16 @@ static const u_char* extract_http_xff(HI_SESSION* session, const u_char* p, cons new IP differs from the current IP. If so, replace it and post an alert. */ if (*true_ip) { - if (!sfip_equals(*true_ip, tmp)) + if (!(*true_ip)->equals(*tmp)) { - sfip_free(*true_ip); + delete *true_ip; *true_ip = tmp; if ((hdrs_args->true_clnt_xff & XFF_HEADERS) == 0) hi_set_event(GID_HTTP_CLIENT, HI_CLIENT_MULTIPLE_TRUEIP_IN_SESSION); } else - sfip_free(tmp); + delete tmp; } else *true_ip = tmp; diff --git a/extra/src/inspectors/http_server/hi_main.cc b/extra/src/inspectors/http_server/hi_main.cc index a97335d83..71b0b5609 100644 --- a/extra/src/inspectors/http_server/hi_main.cc +++ b/extra/src/inspectors/http_server/hi_main.cc @@ -362,8 +362,8 @@ int PrintGlobalConf(HTTPINSPECT_GLOBAL_CONF* GlobalConf) static inline int SetSiInput(HI_SI_INPUT* SiInput, Packet* p) { - sfip_copy(SiInput->sip, p->ptrs.ip_api.get_src()); - sfip_copy(SiInput->dip, p->ptrs.ip_api.get_dst()); + SiInput->sip.set(*p->ptrs.ip_api.get_src()); + SiInput->dip.set(*p->ptrs.ip_api.get_dst()); SiInput->sport = p->ptrs.sp; SiInput->dport = p->ptrs.dp; @@ -1176,7 +1176,7 @@ void FreeHttpSessionData(void* data) snort_free(hsd->log_state); if (hsd->true_ip) - sfip_free(hsd->true_ip); + delete hsd->true_ip; if (hsd->mime_ssn) delete hsd->mime_ssn; @@ -1198,7 +1198,7 @@ int GetHttpTrueIP(Flow* flow, uint8_t** buf, uint32_t* len, uint32_t* type) if (!hsd->true_ip) return 0; - if (hsd->true_ip->family == AF_INET6) + if (hsd->true_ip->is_ip6()) { *type = EVENT_INFO_XFF_IPV6; *len = sizeof(struct in6_addr); /*ipv6 address size in bytes*/ @@ -1209,7 +1209,7 @@ int GetHttpTrueIP(Flow* flow, uint8_t** buf, uint32_t* len, uint32_t* type) *len = sizeof(struct in_addr); /*ipv4 address size in bytes*/ } - *buf = hsd->true_ip->ip8; + *buf = (uint8_t*) hsd->true_ip->get_ptr(); return 1; } diff --git a/extra/src/inspectors/http_server/hi_main.h b/extra/src/inspectors/http_server/hi_main.h index 25f1bc0ce..60be51e8d 100644 --- a/extra/src/inspectors/http_server/hi_main.h +++ b/extra/src/inspectors/http_server/hi_main.h @@ -123,7 +123,7 @@ typedef struct _HttpSessionData HTTP_RESP_STATE resp_state; DECOMPRESS_STATE* decomp_state; HTTP_LOG_STATE* log_state; - sfip_t* true_ip; + SfIp* true_ip; UtfDecodeSession* utf_state; uint8_t log_flags; uint8_t cli_small_chunk_count; diff --git a/extra/src/inspectors/http_server/hi_si.cc b/extra/src/inspectors/http_server/hi_si.cc index 826b442d4..bb1d934e0 100644 --- a/extra/src/inspectors/http_server/hi_si.cc +++ b/extra/src/inspectors/http_server/hi_si.cc @@ -82,22 +82,13 @@ static int InitServerConf(HTTPINSPECT_CONF* GlobalConf, int iServerSip; int iServerDip; int http_id_found = 0; - sfip_t sip; - sfip_t dip; + SfIp sip; + SfIp dip; //structure copy sip = SiInput->sip; dip = SiInput->dip; - if (sip.family == AF_INET) - { - sip.ip32[0] = ntohl(sip.ip32[0]); - } - if (dip.family == AF_INET) - { - dip.ip32[0] = ntohl(dip.ip32[0]); - } - ServerConfDip = ServerConfSip = GlobalConf; /* diff --git a/extra/src/inspectors/http_server/hi_si.h b/extra/src/inspectors/http_server/hi_si.h index f0449188d..a958c5621 100644 --- a/extra/src/inspectors/http_server/hi_si.h +++ b/extra/src/inspectors/http_server/hi_si.h @@ -40,7 +40,7 @@ #include "hi_client.h" #include "hi_server.h" #include "hi_ad.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" struct Packet; @@ -107,8 +107,8 @@ struct HI_SESSION */ typedef struct s_HI_SI_INPUT { - sfip_t sip; - sfip_t dip; + SfIp sip; + SfIp dip; unsigned short sport; unsigned short dport; unsigned char pdir; diff --git a/src/actions/act_react.cc b/src/actions/act_react.cc index dd3f3e8f3..57c85880d 100644 --- a/src/actions/act_react.cc +++ b/src/actions/act_react.cc @@ -61,6 +61,7 @@ #include "framework/ips_action.h" #include "framework/parameter.h" #include "framework/module.h" +#include "utils/util.h" #define s_name "react" diff --git a/src/codecs/ip/cd_icmp4.cc b/src/codecs/ip/cd_icmp4.cc index 0a2ef0ca8..e552d9fba 100644 --- a/src/codecs/ip/cd_icmp4.cc +++ b/src/codecs/ip/cd_icmp4.cc @@ -22,18 +22,12 @@ #include "config.h" #endif +#include "codecs/codec_module.h" +#include "codecs/ip/checksum.h" #include "framework/codec.h" +#include "log/text_log.h" #include "main/snort_config.h" #include "protocols/icmp4.h" -#include "codecs/ip/checksum.h" -#include "codecs/codec_module.h" -#include "protocols/protocol_ids.h" -#include "protocols/packet.h" -#include "protocols/ipv4_options.h" -#include "packet_io/active.h" -#include "log/text_log.h" -#include "main/snort_debug.h" -#include "sfip/sf_ip.h" #define CD_ICMP4_NAME "icmp4" #define CD_ICMP4_HELP "support for Internet control message protocol v4" @@ -240,7 +234,7 @@ bool Icmp4Codec::decode(const RawData& raw, CodecData& codec,DecodeData& snort) void Icmp4Codec::ICMP4AddrTests(const DecodeData& snort, const CodecData& codec) { - uint32_t dst = snort.ip_api.get_dst()->ip32[0]; + uint32_t dst = snort.ip_api.get_dst()->get_ip4_value(); // check all 32 bits; all set so byte order is irrelevant ... if ( dst == ip::IP4_BROADCAST ) @@ -435,13 +429,13 @@ void Icmp4Codec::log(TextLog* const log, const uint8_t* raw_pkt, } /* written this way since inet_ntoa was typedef'ed to use sfip_ntoa - * which requires sfip_t instead of inaddr's. This call to inet_ntoa - * is a rare case that doesn't use sfip_t's. */ + * which requires SfIp instead of inaddr's. This call to inet_ntoa + * is a rare case that doesn't use SfIp's. */ // XXX-IPv6 NOT YET IMPLEMENTED - IPV6 addresses technically not supported - need to change ICMP /* no inet_ntop in Windows */ - sfip_raw_ntop(AF_INET, (const void*)(&icmph->s_icmp_gwaddr.s_addr), + snort_inet_ntop(AF_INET, (const void*)(&icmph->s_icmp_gwaddr.s_addr), buf, sizeof(buf)); TextLog_Print(log, " NEW GW: %s", buf); break; diff --git a/src/codecs/ip/cd_icmp6.cc b/src/codecs/ip/cd_icmp6.cc index 4845ce3b1..eb7fd6693 100644 --- a/src/codecs/ip/cd_icmp6.cc +++ b/src/codecs/ip/cd_icmp6.cc @@ -32,6 +32,7 @@ #include "packet_io/active.h" #include "log/text_log.h" #include "main/snort_debug.h" +#include "utils/util.h" #define CD_ICMP6_NAME "icmp6" #define CD_ICMP6_HELP "support for Internet control message protocol v6" @@ -136,8 +137,8 @@ bool Icmp6Codec::decode(const RawData& raw, CodecData& codec, DecodeData& snort) { bad_cksum_cnt = &stats.bad_ip6_cksum; checksum::Pseudoheader6 ph6; - COPY4(ph6.sip, snort.ip_api.get_src()->ip32); - COPY4(ph6.dip, snort.ip_api.get_dst()->ip32); + COPY4(ph6.sip, snort.ip_api.get_src()->get_ip6_ptr()); + COPY4(ph6.dip, snort.ip_api.get_dst()->get_ip6_ptr()); ph6.zero = 0; ph6.protocol = codec.ip6_csum_proto; ph6.len = htons((u_short)raw.len); @@ -349,8 +350,8 @@ void Icmp6Codec::update(const ip::IpApi& api, const EncodeFlags flags, checksum::Pseudoheader6 ps6; h->cksum = 0; - memcpy(ps6.sip, api.get_src()->ip32, sizeof(ps6.sip)); - memcpy(ps6.dip, api.get_dst()->ip32, sizeof(ps6.dip)); + memcpy(ps6.sip, api.get_src()->get_ip6_ptr(), sizeof(ps6.sip)); + memcpy(ps6.dip, api.get_dst()->get_ip6_ptr(), sizeof(ps6.dip)); ps6.zero = 0; ps6.protocol = IpProtocol::ICMPV6; ps6.len = htons((uint16_t)updated_len); diff --git a/src/codecs/ip/cd_ipv6.cc b/src/codecs/ip/cd_ipv6.cc index 28e1a0306..f8841f9aa 100644 --- a/src/codecs/ip/cd_ipv6.cc +++ b/src/codecs/ip/cd_ipv6.cc @@ -222,7 +222,7 @@ void Ipv6Codec::IPV6CheckIsatap(const ip::IP6Hdr* const ip6h, fe80:0000:0000:0000:0000:5efe, followed by the IPv4 address. */ if (isatap_interface_id == 0x00005EFE) { - if (snort.ip_api.get_src()->ip32[0] != ip6h->ip6_src.u6_addr32[3]) + if (snort.ip_api.get_src()->get_ip4_value() != ip6h->ip6_src.u6_addr32[3]) codec_event(codec, DECODE_IPV6_ISATAP_SPOOF); } } @@ -230,31 +230,27 @@ void Ipv6Codec::IPV6CheckIsatap(const ip::IP6Hdr* const ip6h, void Ipv6Codec::IPV6MiscTests(const DecodeData& snort, const CodecData& codec) { - const sfip_t* ip_src = snort.ip_api.get_src(); - const sfip_t* ip_dst = snort.ip_api.get_dst(); + const SfIp* ip_src = snort.ip_api.get_src(); + const SfIp* ip_dst = snort.ip_api.get_dst(); /* * Some IP Header tests * Land Attack(same src/dst ip) * Loopback (src or dst in 127/8 block) * Modified: 2/22/05-man for High Endian Architecture. - * - * some points in the code assume an IP of 0.0.0.0 matches anything, but - * that is not so here. The sfip_compare makes that assumption for - * compatibility, but sfip_contains does not. Hence, sfip_contains - * is used here in the interrim. */ - if ( sfip_contains(ip_src, ip_dst) == SFIP_CONTAINS) + */ + if (ip_src->fast_eq6(*ip_dst)) { codec_event(codec, DECODE_BAD_TRAFFIC_SAME_SRCDST); } - if (sfip_is_loopback(ip_src) || sfip_is_loopback(ip_dst)) + if (ip_src->is_loopback() || ip_dst->is_loopback()) { codec_event(codec, DECODE_BAD_TRAFFIC_LOOPBACK); } /* Other decoder alerts for IPv6 addresses Added: 5/24/10 (Snort 2.9.0) */ - if (!sfip_is_set(ip_dst)) + if (!ip_dst->is_set()) { codec_event(codec, DECODE_IPV6_DST_ZERO); } diff --git a/src/codecs/ip/cd_tcp.cc b/src/codecs/ip/cd_tcp.cc index 3a36f210f..6f4927946 100644 --- a/src/codecs/ip/cd_tcp.cc +++ b/src/codecs/ip/cd_tcp.cc @@ -37,6 +37,7 @@ #include "log/log_text.h" #include "log/log.h" #include "protocols/packet_manager.h" +#include "utils/util.h" #define CD_TCP_NAME "tcp" #define CD_TCP_HELP "support for transmission control protocol" diff --git a/src/codecs/ip/cd_udp.cc b/src/codecs/ip/cd_udp.cc index 959da7ed8..f6cc00693 100644 --- a/src/codecs/ip/cd_udp.cc +++ b/src/codecs/ip/cd_udp.cc @@ -38,6 +38,7 @@ #include "parser/config_file.h" #include "main/snort_config.h" #include "main/snort_debug.h" +#include "utils/util.h" #define CD_UDP_NAME "udp" #define CD_UDP_HELP "support for user datagram protocol" diff --git a/src/codecs/misc/cd_user.cc b/src/codecs/misc/cd_user.cc index 9a1548f16..513636a2c 100644 --- a/src/codecs/misc/cd_user.cc +++ b/src/codecs/misc/cd_user.cc @@ -48,9 +48,9 @@ void UserCodec::get_data_link_type(std::vector& v) static void set_ip(const DAQ_UsrHdr_t* pci, CodecData& codec, DecodeData& snort) { // FIXIT-M support ip6 - sfip_t sip, dip; - sfip_set_raw(&sip, &pci->src_addr, AF_INET); - sfip_set_raw(&dip, &pci->dst_addr, AF_INET); + SfIp sip, dip; + sip.set(&pci->src_addr, AF_INET); + dip.set(&pci->dst_addr, AF_INET); snort.ip_api.set(sip, dip); snort.sp = pci->src_port; @@ -65,9 +65,9 @@ static void set_ip(const DAQ_UsrHdr_t* pci, CodecData& codec, DecodeData& snort) static void set_key(CodecData& codec, DecodeData& snort) { // FIXIT-L make configurable - sfip_t sip, dip; - sfip_pton("192.168.1.1", &sip); - sfip_pton("192.168.2.2", &dip); + SfIp sip, dip; + sip.set("192.168.1.1"); + dip.set("192.168.2.2"); snort.ip_api.set(sip, dip); snort.sp = 12345; diff --git a/src/detection/detect.cc b/src/detection/detect.cc index 307285ea8..1a62e18ef 100644 --- a/src/detection/detect.cc +++ b/src/detection/detect.cc @@ -294,7 +294,7 @@ static int CheckAddrPort( Packet* p, uint32_t flags, int mode) { - const sfip_t* pkt_addr; /* packet IP address */ + const SfIp* pkt_addr; /* packet IP address */ u_short pkt_port; /* packet port */ int global_except_addr_flag = 0; /* global exception flag is set */ int any_port_flag = 0; /* any port flag set */ @@ -344,7 +344,7 @@ static int CheckAddrPort( } } - DebugFormat(DEBUG_DETECT, "addr %s, port %d ", sfip_to_str(pkt_addr), pkt_port); + DebugFormat(DEBUG_DETECT, "addr %s, port %d ", pkt_addr->ntoa(), pkt_port); if (!rule_addr) goto bail; diff --git a/src/detection/fp_detect.cc b/src/detection/fp_detect.cc index 2df4da52c..554cbfa96 100644 --- a/src/detection/fp_detect.cc +++ b/src/detection/fp_detect.cc @@ -198,8 +198,8 @@ int fpLogEvent(const RuleTreeNode* rtn, const OptTreeNode* otn, Packet* p) } else { - sfip_t cleared; - sfip_clear(cleared); + SfIp cleared; + cleared.clear(); filterEvent = sfthreshold_test( otn->sigInfo.generator, diff --git a/src/detection/service_map.cc b/src/detection/service_map.cc index 10a43387b..f23de8428 100644 --- a/src/detection/service_map.cc +++ b/src/detection/service_map.cc @@ -46,6 +46,7 @@ #include "main/snort_config.h" #include "parser/parser.h" #include "utils/sflsq.h" +#include "utils/util.h" #include "fp_create.h" #include "treenodes.h" diff --git a/src/detection/tag.cc b/src/detection/tag.cc index 569ddff48..abd00ca26 100644 --- a/src/detection/tag.cc +++ b/src/detection/tag.cc @@ -38,7 +38,6 @@ #include "parser/parser.h" #include "events/event.h" #include "hash/sfxhash.h" -#include "sfip/sfip_t.h" #include "sfip/sf_ip.h" /* D E F I N E S **************************************************/ @@ -57,15 +56,18 @@ /* D A T A S T R U C T U R E S **********************************/ /**Key used for identifying a session or host. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" struct tTagFlowKey { - sfip_t sip; ///source IP address - sfip_t dip; ///destination IP address + SfIp sip; ///source IP address + SfIp dip; ///destination IP address /* ports */ uint16_t sp; ///source port uint16_t dp; ///destination port }; +#pragma GCC diagnostic pop /**Node identifying a session or host based tagging. */ @@ -147,7 +149,7 @@ static inline unsigned int memory_per_node( } else if (hash == host_tag_cache_ptr) { - return sizeof(sfip_t)+sizeof(SFXHASH_NODE)+sizeof(TagNode); + return sizeof(SfIp)+sizeof(SFXHASH_NODE)+sizeof(TagNode); } return 0; @@ -259,7 +261,7 @@ void TagCacheReset() */ static inline void SwapTag(TagNode* np) { - sfip_t tip; + SfIp tip; uint16_t tport; tip = np->key.sip; @@ -287,7 +289,7 @@ void InitTag() host_tag_cache_ptr = sfxhash_new( hashTableSize, /* number of hash buckets */ - sizeof(sfip_t), /* size of the key we're going to use */ + sizeof(SfIp), /* size of the key we're going to use */ 0, /* size of the storage node */ 0, /* disable memcap*/ 0, /* use auto node recovery */ @@ -379,8 +381,8 @@ static void AddTagNode(Packet* p, TagData* tag, int mode, uint32_t now, return; } - sfip_copy(idx->key.sip, p->ptrs.ip_api.get_src()); - sfip_copy(idx->key.dip, p->ptrs.ip_api.get_dst()); + idx->key.sip.set(*p->ptrs.ip_api.get_src()); + idx->key.dip.set(*p->ptrs.ip_api.get_dst()); idx->key.sp = p->ptrs.sp; idx->key.dp = p->ptrs.dp; idx->metric = tag->tag_metric; @@ -479,8 +481,8 @@ int CheckTagList(Packet* p, Event* event, void** log_list) DebugMessage(DEBUG_FLOW, "[*] Checking session tag list (forward)...\n"); - sfip_copy(idx.key.sip, p->ptrs.ip_api.get_src()); - sfip_copy(idx.key.dip, p->ptrs.ip_api.get_dst()); + idx.key.sip.set(*p->ptrs.ip_api.get_src()); + idx.key.dip.set(*p->ptrs.ip_api.get_dst()); idx.key.sp = p->ptrs.sp; idx.key.dp = p->ptrs.dp; @@ -489,8 +491,8 @@ int CheckTagList(Packet* p, Event* event, void** log_list) if (returned == NULL) { - sfip_copy(idx.key.dip, p->ptrs.ip_api.get_src()); - sfip_copy(idx.key.sip, p->ptrs.ip_api.get_dst()); + idx.key.dip.set(*p->ptrs.ip_api.get_src()); + idx.key.sip.set(*p->ptrs.ip_api.get_dst()); idx.key.dp = p->ptrs.sp; idx.key.sp = p->ptrs.dp; @@ -510,7 +512,7 @@ int CheckTagList(Packet* p, Event* event, void** log_list) ** Only switch sip, because that's all we check for ** the host tags. */ - sfip_copy(idx.key.sip, p->ptrs.ip_api.get_src()); + idx.key.sip.set(*p->ptrs.ip_api.get_src()); returned = (TagNode*)sfxhash_find(host_tag_cache_ptr, &idx); } @@ -704,17 +706,17 @@ void SetTags(Packet* p, const OptTreeNode* otn, uint16_t event_id) case TAG_SESSION: DebugMessage(DEBUG_FLOW,"Setting session tag:\n"); DebugFormat(DEBUG_FLOW,"SIP: %s SP: %d ", - sfip_ntoa(p->ptrs.ip_api.get_src()), p->ptrs.sp); + p->ptrs.ip_api.get_src()->ntoa(), p->ptrs.sp); DebugFormat(DEBUG_FLOW,"DIP: %s DP: %d\n", - sfip_ntoa(p->ptrs.ip_api.get_dst()),p->ptrs.dp); + p->ptrs.ip_api.get_dst()->ntoa(), p->ptrs.dp); TagSession(p, otn->tag, p->pkth->ts.tv_sec, event_id, log_list); break; case TAG_HOST: DebugMessage(DEBUG_FLOW,"Setting host tag:\n"); DebugFormat(DEBUG_FLOW,"SIP: %s SP: %d ", - sfip_ntoa(p->ptrs.ip_api.get_src()),p->ptrs.sp); + p->ptrs.ip_api.get_src()->ntoa(), p->ptrs.sp); DebugFormat(DEBUG_FLOW, "DIP: %s DP: %d\n", - sfip_ntoa(p->ptrs.ip_api.get_dst()),p->ptrs.dp); + p->ptrs.ip_api.get_dst()->ntoa(), p->ptrs.dp); TagHost(p, otn->tag, p->pkth->ts.tv_sec, event_id, log_list); break; diff --git a/src/file_api/circular_buffer.cc b/src/file_api/circular_buffer.cc index d36d16eac..dff9290e0 100644 --- a/src/file_api/circular_buffer.cc +++ b/src/file_api/circular_buffer.cc @@ -32,12 +32,8 @@ #include "circular_buffer.h" -#include -#include #include "utils/util.h" -#include "main/snort_types.h" - /* Circular buffer object */ struct _CircularBuffer { diff --git a/src/file_api/file_api.h b/src/file_api/file_api.h index 5cc4c5b2d..9f1c68bf7 100644 --- a/src/file_api/file_api.h +++ b/src/file_api/file_api.h @@ -26,7 +26,6 @@ // Currently, it provides three sets of APIs: file processing, MIME processing, // and configurations. -#include #include #include "main/snort_types.h" diff --git a/src/file_api/file_cache.cc b/src/file_api/file_cache.cc index 4e56a59b7..84ee83341 100644 --- a/src/file_api/file_cache.cc +++ b/src/file_api/file_cache.cc @@ -21,13 +21,9 @@ #include "log/messages.h" #include "main/snort_config.h" -#include "sfip/sfip_t.h" -#include "sfip/sf_ip.h" +#include "main/snort_debug.h" #include "time/packet_time.h" -#include "utils/util.h" -#include "utils/snort_bounds.h" -#include "file_service.h" #include "file_stats.h" static int file_cache_free_func(void*, void* data) diff --git a/src/file_api/file_cache.h b/src/file_api/file_cache.h index 60c58da46..33912895f 100644 --- a/src/file_api/file_cache.h +++ b/src/file_api/file_cache.h @@ -23,24 +23,25 @@ #include -#include "file_api.h" -#include "file_lib.h" -#include "file_config.h" - -#include "protocols/packet.h" #include "hash/sfxhash.h" -#include "hash/hashes.h" +#include "sfip/sf_ip.h" + +#include "file_config.h" class FileCache { public: - +// FIXIT-L Merge definition with duplicate in file_enforcer.h? +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" struct FileHashKey { - sfip_t sip; - sfip_t dip; + SfIp sip; + SfIp dip; + uint32_t padding; uint64_t file_sig; }; +#pragma GCC diagnostic pop struct FileNode { @@ -54,12 +55,10 @@ public: FileContext* find(const FileHashKey&); private: - /* The hash table of expected files */ SFXHASH* fileHash = nullptr; uint32_t timeout = DEFAULT_FILE_BLOCK_TIMEOUT; std::mutex cache_mutex; - }; #endif diff --git a/src/file_api/file_capture.cc b/src/file_api/file_capture.cc index dd0ff6746..403134616 100644 --- a/src/file_api/file_capture.cc +++ b/src/file_api/file_capture.cc @@ -44,6 +44,7 @@ #include "utils/stats.h" #include "file_config.h" +#include "file_mempool.h" #include "file_stats.h" FileMemPool* FileCapture::file_mempool = nullptr; diff --git a/src/file_api/file_capture.h b/src/file_api/file_capture.h index 5c8817edd..60a3f6486 100644 --- a/src/file_api/file_capture.h +++ b/src/file_api/file_capture.h @@ -37,8 +37,9 @@ #include #include "file_api.h" -#include "file_lib.h" -#include "file_mempool.h" + +class FileInfo; +class FileMemPool; struct FileCaptureBlock { diff --git a/src/file_api/file_config.cc b/src/file_api/file_config.cc index 33fd7d243..914d8f9d6 100644 --- a/src/file_api/file_config.cc +++ b/src/file_api/file_config.cc @@ -28,13 +28,9 @@ #ifdef HAVE_CONFIG_H #include "config.h" #endif -#include -#include -#include "parser/parse_utils.h" -#include "main/snort_debug.h" #include "main/snort_config.h" -#include "main/snort_types.h" +#include "parser/parse_utils.h" bool FileConfig::process_file_magic(FileMagicData& magic) { diff --git a/src/file_api/file_config.h b/src/file_api/file_config.h index b77d96fdb..678faa92e 100644 --- a/src/file_api/file_config.h +++ b/src/file_api/file_config.h @@ -24,7 +24,6 @@ // This provides the basic configuration for file processing -#include "file_api/file_lib.h" #include "file_api/file_identifier.h" #include "file_api/file_policy.h" diff --git a/src/file_api/file_enforcer.cc b/src/file_api/file_enforcer.cc index fac8117e9..43d7b72e2 100644 --- a/src/file_api/file_enforcer.cc +++ b/src/file_api/file_enforcer.cc @@ -24,23 +24,13 @@ */ #include "file_enforcer.h" -#include "file_service.h" -#include "file_api.h" -#include "file_lib.h" -#include "framework/data_bus.h" -#include "hash/hashes.h" -#include "hash/sfxhash.h" #include "log/messages.h" -#include "main/snort_types.h" -#include "managers/action_manager.h" +#include "main/snort_debug.h" #include "packet_io/active.h" -#include "protocols/packet.h" -#include "sfip/sfip_t.h" -#include "sfip/sf_ip.h" #include "time/packet_time.h" -#include "utils/util.h" -#include "utils/snort_bounds.h" + +#include "file_service.h" static int file_node_free_func(void*, void* data) { @@ -114,8 +104,9 @@ int FileEnforcer::store_verdict(Flow* flow, FileInfo* file) time_t now = packet_time(); FileHashKey hashKey; - sfip_copy(hashKey.dip, &(flow->client_ip)); - sfip_copy(hashKey.sip, &(flow->server_ip)); + hashKey.dip.set(flow->client_ip); + hashKey.sip.set(flow->server_ip); + hashKey.padding = 0; hashKey.file_sig = file_sig; FileNode* node; @@ -199,7 +190,6 @@ FileVerdict FileEnforcer::cached_verdict_lookup(Flow* flow, FileInfo* file) { FileVerdict verdict = FILE_VERDICT_UNKNOWN; SFXHASH_NODE* hash_node; - FileHashKey hashKey; FileNode* node; /* No hash table, or its empty? Get out of dodge. */ @@ -214,8 +204,10 @@ FileVerdict FileEnforcer::cached_verdict_lookup(Flow* flow, FileInfo* file) if (!file_sig) return verdict; - sfip_copy(hashKey.dip, &(flow->client_ip)); - sfip_copy(hashKey.sip, &(flow->server_ip)); + FileHashKey hashKey; + hashKey.dip.set(flow->client_ip); + hashKey.sip.set(flow->server_ip); + hashKey.padding = 0; hashKey.file_sig = file_sig; hash_node = sfxhash_find_node(fileHash, &hashKey); diff --git a/src/file_api/file_enforcer.h b/src/file_api/file_enforcer.h index 02a8eb474..5b28903a2 100644 --- a/src/file_api/file_enforcer.h +++ b/src/file_api/file_enforcer.h @@ -26,28 +26,18 @@ // to request the file data left. To block the new session, we use URL and IPs // to continue blocking the same file. -#include "file_api.h" -#include "file_lib.h" -#include "file_config.h" - -#include "protocols/packet.h" #include "hash/sfxhash.h" -#include "hash/hashes.h" +#include "sfip/sf_ip.h" + +#include "file_config.h" class FileInfo; +#define MAX_FILES_TRACKED 16384 +#define MAX_MEMORY_USED (10*1024*1024) // 10M + class FileEnforcer { - struct FileHashKey - { - sfip_t sip; - sfip_t dip; - size_t file_sig; - }; - - #define MAX_FILES_TRACKED 16384 - #define MAX_MEMORY_USED (10*1024*1024) // 10M - public: struct FileNode { @@ -61,6 +51,18 @@ public: bool apply_verdict(Flow*, FileInfo*, FileVerdict); private: +// FIXIT-L Merge definition with duplicate in file_cache.h? +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" + struct FileHashKey + { + SfIp sip; + SfIp dip; + uint32_t padding; + uint64_t file_sig; + }; +#pragma GCC diagnostic pop + void update_file_node(FileNode*, FileInfo*); FileVerdict check_verdict(Flow*, FileNode*, SFXHASH_NODE*); int store_verdict(Flow*, FileInfo*); diff --git a/src/file_api/file_flows.cc b/src/file_api/file_flows.cc index 4310dc64d..409068fb5 100644 --- a/src/file_api/file_flows.cc +++ b/src/file_api/file_flows.cc @@ -29,23 +29,11 @@ #include "config.h" #endif -#include -#include -#include +#include "protocols/packet.h" -#include "file_service.h" -#include "file_api.h" -#include "file_capture.h" #include "file_cache.h" -#include "file_enforcer.h" -#include "file_policy.h" #include "file_lib.h" -#include "file_config.h" - -#include "main/snort_types.h" -#include "packet_io/active.h" -#include "sfip/sfip_t.h" -#include "sfip/sf_ip.h" +#include "file_service.h" unsigned FileFlows::flow_id = 0; @@ -135,8 +123,9 @@ FileContext* FileFlows::get_file_context(uint64_t file_id, bool to_create) assert(file_cache); FileCache::FileHashKey key; - sfip_copy(key.dip, &(flow->client_ip)); - sfip_copy(key.sip, &(flow->server_ip)); + key.dip.set(flow->client_ip); + key.sip.set(flow->server_ip); + key.padding = 0; key.file_sig = file_id; FileContext* context = file_cache->find(key); diff --git a/src/file_api/file_flows.h b/src/file_api/file_flows.h index 0c74892b7..096bbac0a 100644 --- a/src/file_api/file_flows.h +++ b/src/file_api/file_flows.h @@ -23,9 +23,10 @@ // This provides a wrapper to manage several file contexts -#include +#include "flow/flow.h" #include "main/snort_types.h" -#include "file_lib.h" + +#include "file_api.h" class FileContext; class Flow; diff --git a/src/file_api/file_identifier.cc b/src/file_api/file_identifier.cc index 388a72df2..4a7de85de 100644 --- a/src/file_api/file_identifier.cc +++ b/src/file_api/file_identifier.cc @@ -29,14 +29,11 @@ #include "config.h" #endif -#include +#include #include #include "log/messages.h" -#include "main/snort_types.h" -#include "main/snort_debug.h" -#include "parser/parser.h" #include "utils/util.h" #ifdef UNIT_TEST diff --git a/src/file_api/file_identifier.h b/src/file_api/file_identifier.h index 6b32dcb12..26fb0dad7 100644 --- a/src/file_api/file_identifier.h +++ b/src/file_api/file_identifier.h @@ -27,9 +27,12 @@ // most specific file type is returned. #include -#include "file_lib.h" +#include + #include "hash/sfghash.h" +#include "file_lib.h" + #define FILE_ID_MAX 1024 #define MAX_BRANCH (UINT8_MAX + 1) diff --git a/src/file_api/file_lib.cc b/src/file_api/file_lib.cc index 6d4129dcc..d5efcb936 100644 --- a/src/file_api/file_lib.cc +++ b/src/file_api/file_lib.cc @@ -29,27 +29,21 @@ #include "config.h" #endif -#include -#include -#include -#include - #include #include +#include "hash/hashes.h" +#include "framework/data_bus.h" +#include "main/snort_config.h" +#include "utils/util.h" + #include "file_capture.h" #include "file_config.h" #include "file_enforcer.h" -#include "file_identifier.h" #include "file_service.h" #include "file_segment.h" #include "file_stats.h" -#include "hash/hashes.h" -#include "utils/util.h" -#include "main/snort_config.h" -#include "framework/data_bus.h" - FileInfo::~FileInfo () { if (sha256) diff --git a/src/file_api/file_lib.h b/src/file_api/file_lib.h index 3fa7aab10..5ebac327c 100644 --- a/src/file_api/file_lib.h +++ b/src/file_api/file_lib.h @@ -24,15 +24,13 @@ // This will be basis of file class -#include -#include -#include +#include +#include #include "file_api/file_api.h" -#include "flow/flow.h" -#define SNORT_FILE_TYPE_UNKNOWN UINT16_MAX /**/ -#define SNORT_FILE_TYPE_CONTINUE 0 /**/ +#define SNORT_FILE_TYPE_UNKNOWN UINT16_MAX +#define SNORT_FILE_TYPE_CONTINUE 0 class FileCapture; class FileConfig; diff --git a/src/file_api/file_log.cc b/src/file_api/file_log.cc index ced593347..2316460a6 100644 --- a/src/file_api/file_log.cc +++ b/src/file_api/file_log.cc @@ -21,30 +21,16 @@ #include "config.h" #endif -#include -#include - -#include -#include - -#include "file_config.h" -#include "file_flows.h" -#include "file_lib.h" - -#include "main/snort_debug.h" -#include "main/snort_types.h" #include "framework/data_bus.h" -#include "framework/inspector.h" #include "framework/module.h" #include "log/messages.h" #include "log/text_log.h" -#include "protocols/packet.h" -#include "profiler/profiler.h" -#include "utils/stats.h" -#include "utils/util.h" -#include "flow/flow.h" -#include "sfip/sfip_t.h" #include "time/packet_time.h" +#include "utils/util.h" + +#include "file_config.h" +#include "file_flows.h" +#include "file_lib.h" static const char* s_name = "file_log"; static const char* f_name = "file.log"; @@ -156,8 +142,8 @@ void LogHandler::handle(DataEvent&, Flow* f) TextLog_Print(tlog, " "); } - TextLog_Print(tlog, " %s:%d -> ", sfip_to_str(&f->client_ip), f->client_port); - TextLog_Print(tlog, "%s:%d, ", sfip_to_str(&f->server_ip), f->server_port); + TextLog_Print(tlog, " %s:%d -> ", f->client_ip.ntoa(), f->client_port); + TextLog_Print(tlog, "%s:%d, ", f->server_ip.ntoa(), f->server_port); FileFlows* files = FileFlows::get_file_flows(f); diff --git a/src/file_api/file_mempool.cc b/src/file_api/file_mempool.cc index d75577f0b..d48330080 100644 --- a/src/file_api/file_mempool.cc +++ b/src/file_api/file_mempool.cc @@ -27,10 +27,6 @@ #include "file_mempool.h" -#include -#include -#include - #include "log/messages.h" #include "utils/util.h" diff --git a/src/file_api/file_mempool.h b/src/file_api/file_mempool.h index 785a62bdb..19c6598cc 100644 --- a/src/file_api/file_mempool.h +++ b/src/file_api/file_mempool.h @@ -30,8 +30,8 @@ #include -#include "main/snort_types.h" #include "main/snort_debug.h" + #include "circular_buffer.h" #define FILE_MEM_SUCCESS 0 // FIXIT-L use bool diff --git a/src/file_api/file_module.cc b/src/file_api/file_module.cc index 5933421f9..3ad59c51f 100644 --- a/src/file_api/file_module.cc +++ b/src/file_api/file_module.cc @@ -26,6 +26,7 @@ #include "file_module.h" #include "main/snort_config.h" + #include "file_stats.h" static const Parameter file_magic_params[] = diff --git a/src/file_api/file_module.h b/src/file_api/file_module.h index 5ee240a65..27d393d43 100644 --- a/src/file_api/file_module.h +++ b/src/file_api/file_module.h @@ -22,9 +22,11 @@ #ifndef FILE_MODULE_H #define FILE_MODULE_H -#include "file_config.h" #include "framework/module.h" +#include "file_identifier.h" +#include "file_policy.h" + //------------------------------------------------------------------------- // file_id module //------------------------------------------------------------------------- diff --git a/src/file_api/file_policy.cc b/src/file_api/file_policy.cc index ed7846546..17eafb43c 100644 --- a/src/file_api/file_policy.cc +++ b/src/file_api/file_policy.cc @@ -20,14 +20,10 @@ #include "file_policy.h" -#include -#include -#include +#include "hash/hashes.h" #include "file_capture.h" -#include "file_config.h" #include "file_enforcer.h" -#include "file_lib.h" #include "file_service.h" static FileRule emptyRule; diff --git a/src/file_api/file_segment.cc b/src/file_api/file_segment.cc index 7ee021f93..8e094f39d 100644 --- a/src/file_api/file_segment.cc +++ b/src/file_api/file_segment.cc @@ -19,9 +19,7 @@ #include "file_segment.h" -#include "log/messages.h" -#include "file_flows.h" -#include "file_service.h" +#include "file_lib.h" FileSegment::~FileSegment () { diff --git a/src/file_api/file_segment.h b/src/file_api/file_segment.h index 5a3a1bfc6..59ecb7472 100644 --- a/src/file_api/file_segment.h +++ b/src/file_api/file_segment.h @@ -20,14 +20,14 @@ #ifndef FILE_SEGMENT_H #define FILE_SEGMENT_H -//Segmented file data reassemble and processing +// Segmented file data reassemble and processing -#include #include -#include "file_lib.h" #include "file_api.h" +class Flow; + class FileSegment { public: diff --git a/src/file_api/file_service.cc b/src/file_api/file_service.cc index 094aaf029..5cbefbaf1 100644 --- a/src/file_api/file_service.cc +++ b/src/file_api/file_service.cc @@ -29,28 +29,15 @@ #include "config.h" #endif -#include -#include -#include +#include "main/snort_config.h" +#include "mime/file_mime_process.h" -#include "file_api.h" -#include "file_capture.h" #include "file_cache.h" -#include "file_config.h" -#include "file_flows.h" +#include "file_capture.h" #include "file_enforcer.h" -#include "file_lib.h" +#include "file_flows.h" #include "file_stats.h" -#include "mime/file_mime_config.h" -#include "mime/file_mime_process.h" -#include "main/snort_types.h" -#include "managers/action_manager.h" -#include "detection/detect.h" -#include "detection/detection_util.h" -#include "packet_io/active.h" -#include "framework/inspector.h" - bool FileService::file_type_id_enabled = false; bool FileService::file_signature_enabled = false; bool FileService::file_capture_enabled = false; diff --git a/src/file_api/file_service.h b/src/file_api/file_service.h index 328b5f9a7..6e180faf0 100644 --- a/src/file_api/file_service.h +++ b/src/file_api/file_service.h @@ -24,9 +24,8 @@ // This provides a wrapper to start/stop file service -#include -#include "main/snort_types.h" #include "file_api/file_policy.h" +#include "main/snort_types.h" class FileEnforcer; class FileCache; diff --git a/src/file_api/file_stats.cc b/src/file_api/file_stats.cc index e73f5f21d..0cecb4ab6 100644 --- a/src/file_api/file_stats.cc +++ b/src/file_api/file_stats.cc @@ -24,22 +24,17 @@ ** 5.25.13 - Initial Source Code. Hui Cao */ +#include "file_stats.h" + #ifdef HAVE_CONFIG_H #include #endif -#include -#include +#include "log/messages.h" +#include "utils/stats.h" +#include "utils/util.h" -#include "file_stats.h" #include "file_capture.h" -#include "file_cache.h" -#include "file_config.h" - -#include "main/snort_types.h" -#include "main/snort_config.h" -#include "utils/stats.h" -#include "log/messages.h" THREAD_LOCAL FileCounts file_counts; THREAD_LOCAL FileStats* file_stats = nullptr; diff --git a/src/file_api/file_stats.h b/src/file_api/file_stats.h index 8190ebc14..7d363a117 100644 --- a/src/file_api/file_stats.h +++ b/src/file_api/file_stats.h @@ -22,19 +22,13 @@ #ifndef FILE_STATS_H #define FILE_STATS_H -#include -#include - // FIXIT-M This will be refactored soon -#include "main/thread.h" #include "framework/counts.h" -#include "target_based/snort_protocols.h" -#include "target_based/sftarget_reader.h" +#include "main/thread.h" -#include "main/snort_debug.h" -#include "file_config.h" #include "file_api.h" +#include "file_config.h" #define MAX_PROTOCOL_ORDINAL 8192 // FIXIT-L use std::vector and get_protocol_count() diff --git a/src/filters/detection_filter.cc b/src/filters/detection_filter.cc index eee22542b..be1b6f73a 100644 --- a/src/filters/detection_filter.cc +++ b/src/filters/detection_filter.cc @@ -55,7 +55,7 @@ void detection_filter_print_config(DetectionFilterConfig*) int detection_filter_test( void* pv, - const sfip_t* sip, const sfip_t* dip, + const SfIp* sip, const SfIp* dip, long curtime) { if (pv == NULL) diff --git a/src/filters/detection_filter.h b/src/filters/detection_filter.h index 72a9e938c..1d3e3b3f5 100644 --- a/src/filters/detection_filter.h +++ b/src/filters/detection_filter.h @@ -29,7 +29,7 @@ // and thereby controls event generation. event_filter is evaluated after // the event is queued, and thereby controls which events get logged. -struct sfip_t; +struct SfIp; struct THDX_STRUCT; struct DetectionFilterConfig @@ -48,7 +48,7 @@ void detection_filter_term(); void detection_filter_print_config(DetectionFilterConfig*); void detection_filter_reset_active(); -int detection_filter_test(void*, const sfip_t* sip, const sfip_t* dip, long curtime); +int detection_filter_test(void*, const SfIp* sip, const SfIp* dip, long curtime); void* detection_filter_create(DetectionFilterConfig*, THDX_STRUCT*); #endif diff --git a/src/filters/rate_filter.cc b/src/filters/rate_filter.cc index 491ce03bc..6ee4f8c3a 100644 --- a/src/filters/rate_filter.cc +++ b/src/filters/rate_filter.cc @@ -32,14 +32,15 @@ #include #include -#include "sfrf.h" -#include "sfthd.h" - -#include "utils/util.h" -#include "parser/parser.h" #include "detection/rules.h" #include "main/snort_config.h" +#include "parser/parser.h" +#include "protocols/packet.h" #include "sfip/sf_ip.h" +#include "utils/util.h" + +#include "sfrf.h" +#include "sfthd.h" //static int _printThresholdContext(RateFilterConfig*); @@ -119,9 +120,9 @@ int RateFilter_Test( unsigned gid = otn->sigInfo.generator; unsigned sid = otn->sigInfo.id; - const sfip_t* sip; - const sfip_t* dip; - sfip_t cleared; + const SfIp* sip; + const SfIp* dip; + SfIp cleared; if ( p->ptrs.ip_api.is_ip() ) { @@ -130,7 +131,7 @@ int RateFilter_Test( } else { - sfip_clear(cleared); + cleared.clear(); sip = &cleared; dip = &cleared; } diff --git a/src/filters/sfrf.cc b/src/filters/sfrf.cc index df19ec69f..257552877 100644 --- a/src/filters/sfrf.cc +++ b/src/filters/sfrf.cc @@ -38,6 +38,7 @@ #include "utils/sflsq.h" #include "hash/sfghash.h" #include "hash/sfxhash.h" +#include "sfip/sf_ip.h" #include "sfip/sf_ipvar.h" // Number of hash rows for gid 1 (rules) @@ -51,6 +52,8 @@ // private data ... /* Key to find tracking nodes in trackingHash. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" typedef struct { ///policy identifier. @@ -64,8 +67,10 @@ typedef struct * whether dos threshold is tracking by source or destination IP address. For tracking * by rule, it is cleared out (all 0s). */ - sfip_t ip; + SfIp ip; + uint16_t padding; } tSFRFTrackingNodeKey; +#pragma GCC diagnostic pop /* Tracking node for rate_filter. One node is created on fly, in tracking * hash for each threshold configure (identified by Tid) and source or @@ -111,7 +116,7 @@ static int _checkSamplingPeriod( ); static tSFRFTrackingNode* _getSFRFTrackingNode( - const sfip_t*, + const SfIp*, unsigned tid, time_t curTime ); @@ -120,8 +125,8 @@ static void _updateDependentThresholds( RateFilterConfig* config, unsigned gid, unsigned sid, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, time_t curTime ); @@ -338,14 +343,6 @@ int SFRF_ConfigAdd( return 0; } -#ifdef SFRF_DEBUG -static char* get_netip(const sfip_t* ip) -{ - return sfip_ntoa(ip); -} - -#endif // SFRF_DEBUG - /* * * Find/Test/Add an event against a single threshold object. @@ -363,7 +360,7 @@ static char* get_netip(const sfip_t* ip) */ static int SFRF_TestObject( tSFRFConfigNode* cfgNode, - const sfip_t* ip, + const SfIp* ip, time_t curTime, SFRF_COUNT_OPERATION op ) @@ -422,14 +419,14 @@ static int SFRF_TestObject( #ifdef SFRF_DEBUG printf("--SFRF_DEBUG: %d-%d-%d: %d Packet IP %s, op: %d, count %d, action %d\n", cfgNode->tid, cfgNode->gid, - cfgNode->sid, (unsigned)curTime, get_netip(ip), op, + cfgNode->sid, (unsigned)curTime, ip->ntoa(), op, dynNode->count, retValue); fflush(stdout); #endif return retValue; } -static inline int SFRF_AppliesTo(tSFRFConfigNode* pCfg, const sfip_t* ip) +static inline int SFRF_AppliesTo(tSFRFConfigNode* pCfg, const SfIp* ip) { return ( !pCfg->applyTo || sfvar_ip_in(pCfg->applyTo, ip) ); } @@ -453,8 +450,8 @@ int SFRF_TestThreshold( RateFilterConfig* config, unsigned gid, unsigned sid, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, time_t curTime, SFRF_COUNT_OPERATION op ) @@ -548,8 +545,8 @@ int SFRF_TestThreshold( case SFRF_TRACK_BY_RULE: { - sfip_t cleared; - sfip_clear(cleared); + SfIp cleared; + cleared.clear(); newStatus = SFRF_TestObject(cfgNode, &cleared, curTime, op); } break; @@ -766,8 +763,8 @@ static void _updateDependentThresholds( RateFilterConfig* config, unsigned gid, unsigned sid, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, time_t curTime ) { @@ -788,7 +785,7 @@ static void _updateDependentThresholds( } static tSFRFTrackingNode* _getSFRFTrackingNode( - const sfip_t* ip, + const SfIp* ip, unsigned tid, time_t curTime ) @@ -801,6 +798,7 @@ static tSFRFTrackingNode* _getSFRFTrackingNode( key.ip = *(ip); key.tid = tid; key.policyId = get_network_policy()->policy_id; + key.padding = 0; /* * Check for any Permanent sid objects for this gid or add this one ... diff --git a/src/filters/sfrf.h b/src/filters/sfrf.h index 7acb9d840..2a9f08d5d 100644 --- a/src/filters/sfrf.h +++ b/src/filters/sfrf.h @@ -27,7 +27,7 @@ #include "main/policy.h" #include "actions/actions.h" -struct sfip_t; +struct SfIp; // define to use over rate threshold #define SFRF_OVER_RATE @@ -155,8 +155,8 @@ int SFRF_TestThreshold( RateFilterConfig *config, unsigned gid, unsigned sid, - const sfip_t *sip, - const sfip_t *dip, + const SfIp *sip, + const SfIp *dip, time_t curTime, SFRF_COUNT_OPERATION); diff --git a/src/filters/sfrf_test.cc b/src/filters/sfrf_test.cc index 2426671e8..7ff56c231 100644 --- a/src/filters/sfrf_test.cc +++ b/src/filters/sfrf_test.cc @@ -944,9 +944,9 @@ static int EventTest(EventData* p) // this is the only acceptable public value for op SFRF_COUNT_OPERATION op = SFRF_COUNT_INCREMENT; - sfip_t sip, dip; - sfip_pton(p->sip, &sip); - sfip_pton(p->dip, &dip); + SfIp sip, dip; + sip.set(p->sip); + dip.set(p->dip); status = SFRF_TestThreshold( rfc, p->gid, p->sid, &sip, &dip, curtime, op); diff --git a/src/filters/sfthd.cc b/src/filters/sfthd.cc index cb6b4e1ed..c268a849d 100644 --- a/src/filters/sfthd.cc +++ b/src/filters/sfthd.cc @@ -39,7 +39,7 @@ #include #include -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" #include "sfip/sf_ipvar.h" #include "utils/sflsq.h" #include "hash/sfghash.h" @@ -662,7 +662,7 @@ static char* printIP(unsigned u) #endif int sfthd_test_rule(SFXHASH* rule_hash, THD_NODE* sfthd_node, - const sfip_t* sip, const sfip_t* dip, long curtime) + const SfIp* sip, const SfIp* dip, long curtime) { int status; @@ -676,7 +676,7 @@ int sfthd_test_rule(SFXHASH* rule_hash, THD_NODE* sfthd_node, static inline int sfthd_test_suppress( THD_NODE* sfthd_node, - const sfip_t* ip) + const SfIp* ip) { if ( !sfthd_node->ip_address || sfvar_ip_in(sfthd_node->ip_address, ip) ) @@ -861,14 +861,14 @@ static inline int sfthd_test_non_suppress( int sfthd_test_local( SFXHASH* local_hash, THD_NODE* sfthd_node, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, time_t curtime) { THD_IP_NODE_KEY key; THD_IP_NODE data,* sfthd_ip_node; int status=0; - const sfip_t* ip; + const SfIp* ip; PolicyId policy_id = get_network_policy()->policy_id; @@ -917,6 +917,7 @@ int sfthd_test_local( key.policyId = policy_id; key.ip = *ip; key.thd_id = sfthd_node->thd_id; + key.padding = 0; /* Set up a new data element */ data.count = 1; @@ -956,15 +957,15 @@ static inline int sfthd_test_global( SFXHASH* global_hash, THD_NODE* sfthd_node, unsigned sig_id, /* from current event */ - const sfip_t* sip, /* " */ - const sfip_t* dip, /* " */ + const SfIp* sip, /* " */ + const SfIp* dip, /* " */ time_t curtime) { THD_IP_GNODE_KEY key; THD_IP_NODE data; THD_IP_NODE* sfthd_ip_node; int status=0; - const sfip_t* ip; + const SfIp* ip; PolicyId policy_id = get_network_policy()->policy_id; @@ -1010,6 +1011,7 @@ static inline int sfthd_test_global( key.gen_id = sfthd_node->gen_id; key.sig_id = sig_id; key.policyId = policy_id; + key.padding = 0; /* Set up a new data element */ data.count = 1; @@ -1063,8 +1065,8 @@ int sfthd_test_threshold( THD_STRUCT* thd, unsigned gen_id, unsigned sig_id, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, long curtime) { tThdItemKey key; @@ -1288,9 +1290,9 @@ int sfthd_show_objects(ThresholdObjects* thd_objs) if ( sfthd_node->type == THD_TYPE_SUPPRESS ) { printf(".........ip =%s\n", - sfip_to_str(&sfthd_node->ip_address)); + sfthd_node->ip_address.ntoa()); printf(".........mask =%d\n", - sfip_bits(&sfthd_node->ip_address)); + sfthd_node->ip_address.bits); printf(".........not_flag=%d\n",sfthd_node->ip_mask); } else diff --git a/src/filters/sfthd.h b/src/filters/sfthd.h index e56708650..c3116d046 100644 --- a/src/filters/sfthd.h +++ b/src/filters/sfthd.h @@ -31,7 +31,7 @@ #include "hash/sfghash.h" #include "hash/sfxhash.h" #include "main/policy.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" /*! Max GEN_ID value - Set this to the Max Used by Snort, this is used for the @@ -95,20 +95,25 @@ typedef struct HASH Key to lookup and store Ip nodes. The structure now tracks thresholds for different policies. This destroys locality of reference and may cause poor performance. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" typedef struct { int thd_id; - sfip_t ip; PolicyId policyId; + SfIp ip; + uint16_t padding; } THD_IP_NODE_KEY; typedef struct { unsigned gen_id; unsigned sig_id; - sfip_t ip; PolicyId policyId; + SfIp ip; + uint16_t padding; } THD_IP_GNODE_KEY; +#pragma GCC diagnostic pop /*! THD_NODE @@ -217,7 +222,7 @@ ThresholdObjects* sfthd_objs_new(); void sfthd_objs_free(ThresholdObjects*); int sfthd_test_rule(SFXHASH* rule_hash, THD_NODE* sfthd_node, - const sfip_t* sip, const sfip_t* dip, long curtime); + const SfIp* sip, const SfIp* dip, long curtime); void* sfthd_create_rule_threshold( int id, @@ -250,8 +255,8 @@ int sfthd_test_threshold( THD_STRUCT*, unsigned gen_id, unsigned sig_id, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, long curtime); SFXHASH* sfthd_new_hash(unsigned, size_t, size_t); @@ -259,8 +264,8 @@ SFXHASH* sfthd_new_hash(unsigned, size_t, size_t); int sfthd_test_local( SFXHASH* local_hash, THD_NODE* sfthd_node, - const sfip_t* sip, - const sfip_t* dip, + const SfIp* sip, + const SfIp* dip, time_t curtime); #ifdef THD_DEBUG diff --git a/src/filters/sfthd_test.cc b/src/filters/sfthd_test.cc index 0d154edb6..0239b5339 100644 --- a/src/filters/sfthd_test.cc +++ b/src/filters/sfthd_test.cc @@ -134,7 +134,7 @@ static ThreshData thData[] = ,{ 120, 102, THD_TRK_DST, THD_TYPE_SUPPRESS, 1, 0, IP4_DST, 0, 0, nullptr } // count/seconds < 0 means fire every time ,{ 120, 110, THD_TRK_SRC, THD_TYPE_SUPPRESS, -1, -1, IP4_SRC, 0, 0, nullptr } - // code assumes a valid sfip_t* so can't test this + // code assumes a valid SfIp* so can't test this //,{ 120, 120, THD_TRK_SRC, THD_TYPE_SUPPRESS, 0, 0, "", 0, 0, nullptr } ,{ 120, 130, THD_TRK_SRC, THD_TYPE_LIMIT, -1, 1, IP_ANY, 0, 0, nullptr } ,{ 120, 131, THD_TRK_SRC, THD_TYPE_THRESHOLD, -1, 1, IP_ANY, 0, 0, nullptr } @@ -832,9 +832,9 @@ static int EventTest(EventData* p, void* rule) long curtime = (long)p->now; int status; - sfip_t sip, dip; - sfip_pton(p->sip, &sip); - sfip_pton(p->dip, &dip); + SfIp sip, dip; + sip.set(p->sip); + dip.set(p->dip); if ( rule ) { diff --git a/src/filters/sfthreshold.cc b/src/filters/sfthreshold.cc index 76198f0ef..b9a83f7e5 100644 --- a/src/filters/sfthreshold.cc +++ b/src/filters/sfthreshold.cc @@ -312,7 +312,7 @@ int sfthreshold_create( */ int sfthreshold_test( unsigned gen_id, unsigned sig_id, - const sfip_t* sip, const sfip_t* dip, + const SfIp* sip, const SfIp* dip, long curtime) { if ((snort_conf->threshold_config == NULL) || diff --git a/src/filters/sfthreshold.h b/src/filters/sfthreshold.h index aa7a6750d..aa553e2b4 100644 --- a/src/filters/sfthreshold.h +++ b/src/filters/sfthreshold.h @@ -20,7 +20,7 @@ #ifndef SFTHRESHOLD_H #define SFTHRESHOLD_H -struct sfip_t; +struct SfIp; struct THDX_STRUCT; struct ThresholdObjects; @@ -35,7 +35,7 @@ ThresholdConfig* ThresholdConfigNew(); void ThresholdConfigFree(ThresholdConfig*); void sfthreshold_reset(); int sfthreshold_create(struct SnortConfig*, ThresholdConfig*, THDX_STRUCT*); -int sfthreshold_test(unsigned int, unsigned int, const sfip_t*, const sfip_t*, long curtime); +int sfthreshold_test(unsigned int, unsigned int, const SfIp*, const SfIp*, long curtime); void print_thresholding(ThresholdConfig*, unsigned shutdown); void sfthreshold_reset_active(); void sfthreshold_free(); diff --git a/src/flow/expect_cache.cc b/src/flow/expect_cache.cc index 04162d242..35177973b 100644 --- a/src/flow/expect_cache.cc +++ b/src/flow/expect_cache.cc @@ -116,8 +116,8 @@ ExpectNode* ExpectCache::find_node_by_packet(Packet* p, FlowKey &key) if (!hash_table->get_count()) return nullptr; - const sfip_t* srcIP = p->ptrs.ip_api.get_src(); - const sfip_t* dstIP = p->ptrs.ip_api.get_dst(); + const SfIp* srcIP = p->ptrs.ip_api.get_src(); + const SfIp* dstIP = p->ptrs.ip_api.get_dst(); uint16_t vlanId = (p->proto_bits & PROTO_BIT__VLAN) ? layer::get_vlan_layer(p)->vid() : 0; uint32_t mplsId = (p->proto_bits & PROTO_BIT__MPLS) ? p->ptrs.mplsHdr.label : 0; uint16_t addressSpaceId = p->pkth->address_space_id; @@ -284,8 +284,8 @@ ExpectCache::~ExpectCache() */ int ExpectCache::add_flow(const Packet *ctrlPkt, PktType type, IpProtocol ip_proto, - const sfip_t* cliIP, uint16_t cliPort, - const sfip_t* srvIP, uint16_t srvPort, + const SfIp* cliIP, uint16_t cliPort, + const SfIp* srvIP, uint16_t srvPort, char direction, FlowData* fd, int16_t appId) { /* Just pull the VLAN ID, MPLS ID, and Address Space ID from the diff --git a/src/flow/expect_cache.h b/src/flow/expect_cache.h index f373dba7c..f9c2f66e4 100644 --- a/src/flow/expect_cache.h +++ b/src/flow/expect_cache.h @@ -61,7 +61,6 @@ // a la FlowCache) //------------------------------------------------------------------------- -#include "sfip/sfip_t.h" #include "flow/flow.h" struct Packet; @@ -75,8 +74,8 @@ public: ~ExpectCache(); int add_flow(const Packet *ctrlPkt, PktType, IpProtocol, - const sfip_t* cliIP, uint16_t cliPort, - const sfip_t* srvIP, uint16_t srvPort, + const SfIp* cliIP, uint16_t cliPort, + const SfIp* srvIP, uint16_t srvPort, char direction, FlowData*, int16_t appId = 0); bool is_expected(Packet*); diff --git a/src/flow/flow.cc b/src/flow/flow.cc index c2fdce289..9a300ce80 100644 --- a/src/flow/flow.cc +++ b/src/flow/flow.cc @@ -316,7 +316,7 @@ void Flow::set_direction(Packet* p) if (ip_api->is_ip4()) { - if (sfip_fast_eq4(ip_api->get_src(), &client_ip)) + if (ip_api->get_src()->fast_eq4(client_ip)) { if ( !(p->proto_bits & (PROTO_BIT__TCP | PROTO_BIT__UDP)) ) p->packet_flags |= PKT_FROM_CLIENT; @@ -327,7 +327,7 @@ void Flow::set_direction(Packet* p) else p->packet_flags |= PKT_FROM_SERVER; } - else if (sfip_fast_eq4(ip_api->get_dst(), &client_ip)) + else if (ip_api->get_dst()->fast_eq4(client_ip)) { if ( !(p->proto_bits & (PROTO_BIT__TCP | PROTO_BIT__UDP)) ) p->packet_flags |= PKT_FROM_SERVER; @@ -341,7 +341,7 @@ void Flow::set_direction(Packet* p) } else /* IS_IP6(p) */ { - if (sfip_fast_eq6(ip_api->get_src(), &client_ip)) + if (ip_api->get_src()->fast_eq6(client_ip)) { if ( !(p->proto_bits & (PROTO_BIT__TCP | PROTO_BIT__UDP)) ) p->packet_flags |= PKT_FROM_CLIENT; @@ -352,7 +352,7 @@ void Flow::set_direction(Packet* p) else p->packet_flags |= PKT_FROM_SERVER; } - else if (sfip_fast_eq6(ip_api->get_dst(), &client_ip)) + else if (ip_api->get_dst()->fast_eq6(client_ip)) { if ( !(p->proto_bits & (PROTO_BIT__TCP | PROTO_BIT__UDP)) ) p->packet_flags |= PKT_FROM_SERVER; diff --git a/src/flow/flow.h b/src/flow/flow.h index 1bbcb858b..911c010d4 100644 --- a/src/flow/flow.h +++ b/src/flow/flow.h @@ -29,10 +29,10 @@ #include -#include "sfip/sfip_t.h" #include "flow/flow_key.h" #include "framework/inspector.h" #include "framework/codec.h" +#include "sfip/sf_ip.h" #define SSNFLAG_SEEN_CLIENT 0x00000001 #define SSNFLAG_SEEN_SENDER 0x00000001 @@ -322,8 +322,8 @@ public: // FIXIT-M privatize if possible uint64_t expire_time; - sfip_t client_ip; // FIXIT-L family and bits should be changed to uint16_t - sfip_t server_ip; // or uint8_t to reduce sizeof from 24 to 20 + SfIp client_ip; + SfIp server_ip; LwState ssn_state; LwState previous_ssn_state; diff --git a/src/flow/flow_control.cc b/src/flow/flow_control.cc index 988233b08..bf0dc53b9 100644 --- a/src/flow/flow_control.cc +++ b/src/flow/flow_control.cc @@ -35,6 +35,7 @@ #include "protocols/vlan.h" #include "sfip/sf_ip.h" #include "stream/stream.h" +#include "utils/util.h" #include "expect_cache.h" #include "flow_cache.h" @@ -299,8 +300,8 @@ static bool is_bidirectional(const Flow* flow) static void init_roles_ip(Packet* p, Flow* flow) { flow->ssn_state.direction = FROM_CLIENT; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_src()); - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_dst()); + flow->client_ip.set(*p->ptrs.ip_api.get_src()); + flow->server_ip.set(*p->ptrs.ip_api.get_dst()); } static void init_roles_tcp(Packet* p, Flow* flow) @@ -308,33 +309,33 @@ static void init_roles_tcp(Packet* p, Flow* flow) if ( p->ptrs.tcph->is_syn_only() ) { flow->ssn_state.direction = FROM_CLIENT; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_src()); + flow->client_ip.set(*p->ptrs.ip_api.get_src()); flow->client_port = ntohs(p->ptrs.tcph->th_sport); - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_dst()); + flow->server_ip.set(*p->ptrs.ip_api.get_dst()); flow->server_port = ntohs(p->ptrs.tcph->th_dport); } else if ( p->ptrs.tcph->is_syn_ack() ) { flow->ssn_state.direction = FROM_SERVER; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_dst()); + flow->client_ip.set(*p->ptrs.ip_api.get_dst()); flow->client_port = ntohs(p->ptrs.tcph->th_dport); - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_src()); + flow->server_ip.set(*p->ptrs.ip_api.get_src()); flow->server_port = ntohs(p->ptrs.tcph->th_sport); } else if (p->ptrs.sp > p->ptrs.dp) { flow->ssn_state.direction = FROM_CLIENT; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_src()); + flow->client_ip.set(*p->ptrs.ip_api.get_src()); flow->client_port = ntohs(p->ptrs.tcph->th_sport); - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_dst()); + flow->server_ip.set(*p->ptrs.ip_api.get_dst()); flow->server_port = ntohs(p->ptrs.tcph->th_dport); } else { flow->ssn_state.direction = FROM_SERVER; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_dst()); + flow->client_ip.set(*p->ptrs.ip_api.get_dst()); flow->client_port = ntohs(p->ptrs.tcph->th_dport); - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_src()); + flow->server_ip.set(*p->ptrs.ip_api.get_src()); flow->server_port = ntohs(p->ptrs.tcph->th_sport); } } @@ -342,9 +343,9 @@ static void init_roles_tcp(Packet* p, Flow* flow) static void init_roles_udp(Packet* p, Flow* flow) { flow->ssn_state.direction = FROM_CLIENT; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_src()); + flow->client_ip.set(*p->ptrs.ip_api.get_src()); flow->client_port = ntohs(p->ptrs.udph->uh_sport); - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_dst()); + flow->server_ip.set(*p->ptrs.ip_api.get_dst()); flow->server_port = ntohs(p->ptrs.udph->uh_dport); } @@ -353,17 +354,17 @@ static void init_roles_user(Packet* p, Flow* flow) if ( p->ptrs.decode_flags & DECODE_C2S ) { flow->ssn_state.direction = FROM_CLIENT; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_src()); + flow->client_ip.set(*p->ptrs.ip_api.get_src()); flow->client_port = p->ptrs.sp; - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_dst()); + flow->server_ip.set(*p->ptrs.ip_api.get_dst()); flow->server_port = p->ptrs.dp; } else { flow->ssn_state.direction = FROM_SERVER; - sfip_copy(flow->client_ip, p->ptrs.ip_api.get_dst()); + flow->client_ip.set(*p->ptrs.ip_api.get_dst()); flow->client_port = p->ptrs.dp; - sfip_copy(flow->server_ip, p->ptrs.ip_api.get_src()); + flow->server_ip.set(*p->ptrs.ip_api.get_src()); flow->server_port = p->ptrs.sp; } } @@ -775,8 +776,8 @@ bool FlowControl::expected_flow(Flow* flow, Packet* p) int FlowControl::add_expected( const Packet* ctrlPkt, PktType type, IpProtocol ip_proto, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, char direction, FlowData* fd) { return exp_cache->add_flow( @@ -786,8 +787,8 @@ int FlowControl::add_expected( int FlowControl::add_expected( const Packet* ctrlPkt, PktType type, IpProtocol ip_proto, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, int16_t appId, FlowData* fd) { return exp_cache->add_flow( diff --git a/src/flow/flow_control.h b/src/flow/flow_control.h index 1cc98e232..293b109be 100644 --- a/src/flow/flow_control.h +++ b/src/flow/flow_control.h @@ -38,7 +38,7 @@ class FlowData; class FlowCache; struct FlowKey; struct Packet; -struct sfip_t; +struct SfIp; enum class PruneReason : uint8_t; @@ -79,14 +79,14 @@ public: int add_expected( const Packet* ctrlPkt, PktType, IpProtocol, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, char direction, FlowData*); int add_expected( const Packet* ctrlPkt, PktType, IpProtocol, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, int16_t appId, FlowData*); PegCount get_flows(PktType); diff --git a/src/flow/flow_key.cc b/src/flow/flow_key.cc index dbd4b0dff..9c383c1d6 100644 --- a/src/flow/flow_key.cc +++ b/src/flow/flow_key.cc @@ -37,12 +37,12 @@ inline bool FlowKey::init4( IpProtocol ip_proto, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, uint32_t mplsId, bool order) { - const uint32_t* src; - const uint32_t* dst; + uint32_t src; + uint32_t dst; bool reversed = false; if ( ip_proto == IpProtocol::ICMPV4 ) @@ -58,21 +58,21 @@ inline bool FlowKey::init4( } } - src = srcIP->ip32; - dst = dstIP->ip32; + src = srcIP->get_ip4_value(); + dst = dstIP->get_ip4_value(); /* These comparisons are done in this fashion for performance reasons */ - if ( !order || *src < *dst) + if ( !order || src < dst) { - COPY4(ip_l, src); - COPY4(ip_h, dst); + COPY4(ip_l, srcIP->get_ip6_ptr()); + COPY4(ip_h, dstIP->get_ip6_ptr()); port_l = srcPort; port_h = dstPort; } - else if (*src == *dst) + else if (src == dst) { - COPY4(ip_l, src); - COPY4(ip_h, dst); + COPY4(ip_l, srcIP->get_ip6_ptr()); + COPY4(ip_h, dstIP->get_ip6_ptr()); if (srcPort < dstPort) { port_l = srcPort; @@ -87,14 +87,14 @@ inline bool FlowKey::init4( } else { - COPY4(ip_l, dst); + COPY4(ip_l, dstIP->get_ip6_ptr()); port_l = dstPort; - COPY4(ip_h, src); + COPY4(ip_h, srcIP->get_ip6_ptr()); port_h = srcPort; reversed = true; } if (SnortConfig::mpls_overlapping_ip() && - ip::isPrivateIP(*src) && ip::isPrivateIP(*dst)) + ip::isPrivateIP(src) && ip::isPrivateIP(dst)) mplsLabel = mplsId; else mplsLabel = 0; @@ -104,12 +104,10 @@ inline bool FlowKey::init4( inline bool FlowKey::init6( IpProtocol ip_proto, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, uint32_t mplsId, bool order) { - const sfip_t* src; - const sfip_t* dst; bool reversed = false; if ( ip_proto == IpProtocol::ICMPV4 ) @@ -141,20 +139,17 @@ inline bool FlowKey::init6( } } - src = srcIP; - dst = dstIP; - - if ( !order || sfip_fast_lt6(src, dst)) + if ( !order || srcIP->fast_lt6(*dstIP)) { - COPY4(ip_l, src->ip32); + COPY4(ip_l, srcIP->get_ip6_ptr()); port_l = srcPort; - COPY4(ip_h, dst->ip32); + COPY4(ip_h, dstIP->get_ip6_ptr()); port_h = dstPort; } - else if (sfip_fast_eq6(src, dst)) + else if (srcIP->fast_eq6(*dstIP)) { - COPY4(ip_l, src->ip32); - COPY4(ip_h, dst->ip32); + COPY4(ip_l, srcIP->get_ip6_ptr()); + COPY4(ip_h, dstIP->get_ip6_ptr()); if (srcPort < dstPort) { port_l = srcPort; @@ -169,9 +164,9 @@ inline bool FlowKey::init6( } else { - COPY4(ip_l, dst->ip32); + COPY4(ip_l, dstIP->get_ip6_ptr()); port_l = dstPort; - COPY4(ip_h, src->ip32); + COPY4(ip_h, srcIP->get_ip6_ptr()); port_h = srcPort; reversed = true; } @@ -211,8 +206,8 @@ void FlowKey::init_mpls(uint32_t mplsId) bool FlowKey::init( PktType type, IpProtocol ip_proto, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, uint16_t vlanId, uint32_t mplsId, uint16_t addrSpaceId) { bool reversed; @@ -243,7 +238,7 @@ bool FlowKey::init( bool FlowKey::init( PktType type, IpProtocol ip_proto, - const sfip_t *srcIP, const sfip_t *dstIP, + const SfIp *srcIP, const SfIp *dstIP, uint32_t id, uint16_t vlanId, uint32_t mplsId, uint16_t addrSpaceId) { diff --git a/src/flow/flow_key.h b/src/flow/flow_key.h index 70479e5dc..ce197cad3 100644 --- a/src/flow/flow_key.h +++ b/src/flow/flow_key.h @@ -26,8 +26,10 @@ #include "main/snort_types.h" #include "hash/sfhashfcn.h" #include "framework/decode_data.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" struct FlowKey { uint32_t ip_l[4]; /* Low IP */ @@ -47,13 +49,13 @@ struct FlowKey addresses at this time. */ bool init( PktType, IpProtocol, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, uint16_t vlanId, uint32_t mplsId, uint16_t addrSpaceId); bool init( PktType, IpProtocol, - const sfip_t *srcIP, const sfip_t *dstIP, + const SfIp *srcIP, const SfIp *dstIP, uint32_t id, uint16_t vlanId, uint32_t mplsId, uint16_t addrSpaceId); @@ -68,16 +70,17 @@ struct FlowKey private: bool init4( IpProtocol, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, uint32_t mplsId, bool order = true); bool init6( IpProtocol, - const sfip_t *srcIP, uint16_t srcPort, - const sfip_t *dstIP, uint16_t dstPort, + const SfIp *srcIP, uint16_t srcPort, + const SfIp *dstIP, uint16_t dstPort, uint32_t mplsId, bool order = true); }; +#pragma GCC diagnostic pop #endif diff --git a/src/flow/ha.cc b/src/flow/ha.cc index cb4098067..dad982b0d 100644 --- a/src/flow/ha.cc +++ b/src/flow/ha.cc @@ -215,30 +215,24 @@ static uint8_t write_flow_key(Flow* flow, HAMessage* msg) const FlowKey* key = flow->key; assert(key); - if (is_ip6_key(flow->key) ) + if ( is_ip6_key(flow->key) ) { hdr->key_type = KEY_TYPE_IP6; memcpy(msg->cursor, key, KEY_SIZE_IP6); msg->cursor += KEY_SIZE_IP6; + return KEY_SIZE_IP6; } -// FIXIT-H - remove the #ifdef COMPRESSED_KEY sections when the ip6/ip4 logic is implemented -// and the compressed key is available for use. Until then all keys are IP6 and larger. -#ifdef COMPRESSED_KEY - else - { - hdr->key_type = KEY_TYPE_IP4; - memcpy(msg->cursor, &key->ip_l[3], sizeof(key->ip_l[3])); - msg->cursor += sizeof(key->ip_l[3]); - memcpy(msg->cursor, &key->ip_h[3], sizeof(key->ip_h[3])); - msg->cursor += sizeof(key->ip_h[3]); - memcpy(msg->cursor, ((uint8_t*)key) + 32, KEY_SIZE_IP4 - 8); - msg->cursor += KEY_SIZE_IP4 - 8; - return KEY_SIZE_IP4; - } -#endif - return 0; + hdr->key_type = KEY_TYPE_IP4; + memcpy(msg->cursor, &key->ip_l[3], sizeof(key->ip_l[3])); + msg->cursor += sizeof(key->ip_l[3]); + memcpy(msg->cursor, &key->ip_h[3], sizeof(key->ip_h[3])); + msg->cursor += sizeof(key->ip_h[3]); + memcpy(msg->cursor, ((uint8_t*)key) + 32, KEY_SIZE_IP4 - 8); + msg->cursor += KEY_SIZE_IP4 - 8; + + return KEY_SIZE_IP4; } // Regardless of the message cursor, extract the key and @@ -253,9 +247,9 @@ static uint8_t read_flow_key(FlowKey* key, HAMessage* msg) { memcpy(key, msg->cursor, KEY_SIZE_IP6); msg->cursor += KEY_SIZE_IP6; + return KEY_SIZE_IP6; } -#ifdef COMPRESSED_KEY else if ( hdr->key_type == KEY_TYPE_IP4 ) { /* Lower IPv4 address */ @@ -271,9 +265,9 @@ static uint8_t read_flow_key(FlowKey* key, HAMessage* msg) /* The remainder of the key */ memcpy(((uint8_t*)key) + 32, msg->cursor, KEY_SIZE_IP4 - 8); msg->cursor += KEY_SIZE_IP4 - 8; + return KEY_SIZE_IP4; } -#endif else return 0; } diff --git a/src/flow/session.h b/src/flow/session.h index 535dcc8e9..0a935292e 100644 --- a/src/flow/session.h +++ b/src/flow/session.h @@ -23,10 +23,10 @@ // Session is an abstract base class for the various protocol subclasses. // the subclasses do the actual work of tracking, reassembly, etc. -#include "sfip/sfip_t.h" #include "stream/stream.h" struct Packet; +struct SfIp; class Flow; class Session @@ -35,7 +35,7 @@ public: virtual ~Session() { } virtual bool setup(Packet*) { return true; } - virtual void update_direction(char /*dir*/, const sfip_t*, uint16_t /*port*/) { } + virtual void update_direction(char /*dir*/, const SfIp*, uint16_t /*port*/) { } virtual int process(Packet*) { return 0; } virtual void restart(Packet*) { } diff --git a/src/framework/value.cc b/src/framework/value.cc index c8b70ea29..56c5fadee 100644 --- a/src/framework/value.cc +++ b/src/framework/value.cc @@ -24,7 +24,6 @@ #include #include -#include "sfip/sfip_t.h" #include "sfip/sf_ip.h" #ifdef UNIT_TEST @@ -76,16 +75,28 @@ void Value::get_addr_ip6(uint8_t (&addr)[16]) const memset(addr, 0, sizeof(addr)); } -void Value::get_addr(sfip_t& addr) const +void Value::get_addr(SfIp& addr) const { if ( str.size() == 4 ) - sfip_set_raw(&addr, str.c_str(), AF_INET); + addr.set(str.c_str(), AF_INET); else if ( str.size() == 16 ) - sfip_set_raw(&addr, str.c_str(), AF_INET6); + addr.set(str.c_str(), AF_INET6); else - memset(&addr, 0, sizeof(addr)); + addr.clear(); +} + +void Value::get_addr(SfCidr& cidr) const +{ + if ( str.size() == 4 ) + cidr.set(str.c_str(), AF_INET); + + else if ( str.size() == 16 ) + cidr.set(str.c_str(), AF_INET6); + + else + cidr.clear(); } void Value::get_bits(PortBitSet& list) const diff --git a/src/framework/value.h b/src/framework/value.h index 52cc8e9b7..afcc2c460 100644 --- a/src/framework/value.h +++ b/src/framework/value.h @@ -30,8 +30,9 @@ #include "main/snort_types.h" #include "framework/bits.h" #include "framework/parameter.h" +#include "sfip/sf_cidr.h" -struct sfip_t; +struct SfIp; class SO_PUBLIC Value { @@ -127,7 +128,8 @@ public: void get_addr(uint8_t (&addr)[16]) const; void get_addr_ip4(uint8_t (&addr)[4]) const; void get_addr_ip6(uint8_t (&addr)[16]) const; - void get_addr(sfip_t&) const; + void get_addr(SfIp&) const; + void get_addr(SfCidr&) const; void set_first_token(); bool get_next_token(std::string&); diff --git a/src/hash/sfhashfcn.cc b/src/hash/sfhashfcn.cc index f203025f2..a1958ad2d 100644 --- a/src/hash/sfhashfcn.cc +++ b/src/hash/sfhashfcn.cc @@ -31,9 +31,11 @@ #include "sfhashfcn.h" -#include "sfprimetable.h" #include "main/snort_types.h" #include "main/snort_config.h" +#include "utils/util.h" + +#include "sfprimetable.h" SFHASHFCN* sfhashfcn_new(int m) { diff --git a/src/host_tracker/host_cache.cc b/src/host_tracker/host_cache.cc index 704fe600e..c7ec75f27 100644 --- a/src/host_tracker/host_cache.cc +++ b/src/host_tracker/host_cache.cc @@ -32,12 +32,13 @@ LruCacheShared, HashHostIpKey> void host_cache_add_host_tracker(HostTracker* ht) { std::shared_ptr sptr(ht); - host_cache.insert(ht->get_ip_addr().ip8, sptr); + host_cache.insert((const uint8_t*) ht->get_ip_addr().get_ip6_ptr(), sptr); } -bool host_cache_add_service(sfip_t ipaddr, Protocol ipproto, Port port, const char* /*service*/) +// FIXIT-L ipaddr should probably be a reference +bool host_cache_add_service(SfIp ipaddr, Protocol ipproto, Port port, const char* /*service*/) { - HostIpKey ipkey(ipaddr.ip8); + HostIpKey ipkey((const uint8_t*) ipaddr.get_ip6_ptr()); uint16_t proto = 0; // FIXIT-M not safe with multithreads snort_conf->proto_ref->add(service)); HostApplicationEntry app_entry(ipproto, port, proto); std::shared_ptr ht; diff --git a/src/host_tracker/host_cache.h b/src/host_tracker/host_cache.h index 6cea2fcb3..d23bae4e1 100644 --- a/src/host_tracker/host_cache.h +++ b/src/host_tracker/host_cache.h @@ -69,7 +69,7 @@ extern LruCacheShared, HashHostIpKey> ho void host_cache_add_host_tracker(HostTracker*); // Insert a new service into host cache if it doesn't already exist. -SO_PUBLIC bool host_cache_add_service(sfip_t, Protocol, Port, const char* service); +SO_PUBLIC bool host_cache_add_service(SfIp, Protocol, Port, const char* service); #endif diff --git a/src/host_tracker/host_tracker.h b/src/host_tracker/host_tracker.h index c806557bd..3316a8fdb 100644 --- a/src/host_tracker/host_tracker.h +++ b/src/host_tracker/host_tracker.h @@ -31,7 +31,7 @@ #include #include -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" #include "framework/counts.h" #include "main/thread.h" @@ -82,8 +82,8 @@ private: std::mutex host_tracker_lock; // Ensure that updates to a // shared object are safe. - // FIXIT-M do we need to use a host_id instead of sfip_t as in sfrna? - sfip_t ip_addr; + // FIXIT-M do we need to use a host_id instead of SfIp as in sfrna? + SfIp ip_addr; // Policies to apply to this host. Policy stream_policy = 0; @@ -98,13 +98,13 @@ public: memset(&ip_addr, 0, sizeof(ip_addr)); } - sfip_t get_ip_addr() + SfIp get_ip_addr() { std::lock_guard lck(host_tracker_lock); return ip_addr; } - void set_ip_addr(const sfip_t& new_ip_addr) + void set_ip_addr(const SfIp& new_ip_addr) { std::lock_guard lck(host_tracker_lock); std::memcpy(&ip_addr, &new_ip_addr, sizeof(ip_addr)); diff --git a/src/host_tracker/host_tracker_module.cc b/src/host_tracker/host_tracker_module.cc index ae41f9f2b..61722e1b4 100644 --- a/src/host_tracker/host_tracker_module.cc +++ b/src/host_tracker/host_tracker_module.cc @@ -68,7 +68,7 @@ bool HostTrackerModule::set(const char*, Value& v, SnortConfig* sc) { if ( host and v.is("ip") ) { - sfip_t addr; + SfIp addr; v.get_addr(addr); host->set_ip_addr(addr); } diff --git a/src/host_tracker/test/CMakeLists.txt b/src/host_tracker/test/CMakeLists.txt index b624b7023..c463b4dcf 100644 --- a/src/host_tracker/test/CMakeLists.txt +++ b/src/host_tracker/test/CMakeLists.txt @@ -5,7 +5,7 @@ set ( ${DNET_LIBRARIES} ) -add_cpputest(host_cache_test host_tracker) +add_cpputest(host_cache_test host_tracker sfip) add_cpputest(host_cache_module_test host_tracker ${HOST_TRACKER_MODULE_LIBS} hash) add_cpputest(host_tracker_module_test host_tracker ${HOST_TRACKER_MODULE_LIBS}) -add_cpputest(host_tracker_test host_tracker) +add_cpputest(host_tracker_test host_tracker sfip) diff --git a/src/host_tracker/test/Makefile.am b/src/host_tracker/test/Makefile.am index 51d54e39d..c709486f5 100644 --- a/src/host_tracker/test/Makefile.am +++ b/src/host_tracker/test/Makefile.am @@ -16,6 +16,6 @@ host_tracker_test_CPPFLAGS = $(AM_CPPFLAGS) @CPPUTEST_CPPFLAGS@ host_cache_module_test_LDADD = ../host_cache_module.o ../host_cache.o ../host_tracker.o ../../framework/libframework.a ../../catch/libcatch_tests.a ../../sfip/libsfip.a ../../hash/libhash.a @CPPUTEST_LDFLAGS@ host_tracker_module_test_LDADD = ../host_tracker_module.o ../host_cache.o ../host_tracker.o ../../framework/libframework.a ../../catch/libcatch_tests.a ../../sfip/libsfip.a @CPPUTEST_LDFLAGS@ -host_cache_test_LDADD = ../host_cache.o ../host_tracker.o @CPPUTEST_LDFLAGS@ -host_tracker_test_LDADD = ../host_tracker.o @CPPUTEST_LDFLAGS@ +host_cache_test_LDADD = ../host_cache.o ../host_tracker.o ../../sfip/libsfip.a @CPPUTEST_LDFLAGS@ +host_tracker_test_LDADD = ../host_tracker.o ../../sfip/libsfip.a @CPPUTEST_LDFLAGS@ diff --git a/src/host_tracker/test/host_cache_module_test.cc b/src/host_tracker/test/host_cache_module_test.cc index 75f2dcad3..389b56eec 100644 --- a/src/host_tracker/test/host_cache_module_test.cc +++ b/src/host_tracker/test/host_cache_module_test.cc @@ -50,7 +50,7 @@ char* snort_strdup(const char* s) #define FRAG_POLICY 33 #define STREAM_POLICY 100 -sfip_t expected_addr; +SfIp expected_addr; TEST_GROUP(host_cache_module) { }; diff --git a/src/host_tracker/test/host_cache_test.cc b/src/host_tracker/test/host_cache_test.cc index f8e23b682..44b1778bb 100644 --- a/src/host_tracker/test/host_cache_test.cc +++ b/src/host_tracker/test/host_cache_test.cc @@ -32,6 +32,12 @@ int16_t AddProtocolReference(const char* protocol) return 1; } +// Ditto for snort_strdup() +char* snort_strdup(const char* str) +{ + return strdup(str); +} + TEST_GROUP(host_cache) { }; @@ -73,8 +79,8 @@ TEST(host_cache, host_cache_add_host_tracker_test) std::shared_ptr actual_ht; uint8_t hk[16] = { 0xde,0xad,0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,0x34,0x56,0x78,0x90,0xab,0xcd,0xef }; - sfip_t ip_addr = { 0x1ead,0x1eef, {{0xbe,0xef,0xde,0xad,0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,0x34,0x56,0x78,0x90,0xab}} }; - sfip_t actual_ip_addr; + SfIp ip_addr; + SfIp actual_ip_addr; HostIpKey hkey(hk); Port port = 443; Protocol proto = 6; @@ -82,12 +88,14 @@ TEST(host_cache, host_cache_add_host_tracker_test) HostApplicationEntry actual_app_entry; bool ret; + ip_addr.pton(AF_INET6, "beef:dead:beef:abcd:ef01:2334:5678:90ab"); + expected_ht->set_ip_addr(ip_addr); expected_ht->add_service(app_entry); host_cache_add_host_tracker(expected_ht); - ret = host_cache.find(ip_addr.ip8, actual_ht); + ret = host_cache.find((const uint8_t*) ip_addr.get_ip6_ptr(), actual_ht); CHECK(true == ret); actual_ip_addr = actual_ht->get_ip_addr(); @@ -107,8 +115,8 @@ TEST(host_cache, host_cache_add_service_test) std::shared_ptr actual_ht; uint8_t hk[16] = { 0xde,0xad,0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,0x34,0x56,0x78,0x90,0xab,0xcd,0xef }; - sfip_t ip_addr1 = { 0x1ede,0x1ead, {{0xbe,0xef,0xde,0xad,0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,0x34,0x56,0x78,0x90,0xab}} }; - sfip_t ip_addr2 = { 0x01de,0x05ad, {{0xbe,0xef,0xde,0xad,0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,0x34,0x56,0x78,0x90,0xab}} }; + SfIp ip_addr1; + SfIp ip_addr2; HostIpKey hkey(hk); Port port1 = 443; Port port2 = 22; @@ -119,6 +127,9 @@ TEST(host_cache, host_cache_add_service_test) HostApplicationEntry actual_app_entry; bool ret; + ip_addr1.pton(AF_INET6, "beef:dead:beef:abcd:ef01:2334:5678:90ab"); + ip_addr2.pton(AF_INET6, "beef:dead:beef:abcd:ef01:2334:5678:90ab"); + // Initialize cache with a HostTracker. host_cache_add_host_tracker(expected_ht); @@ -126,7 +137,7 @@ TEST(host_cache, host_cache_add_service_test) ret = host_cache_add_service(ip_addr1, proto1, port1, "udp"); CHECK(true == ret); - ret = host_cache.find(ip_addr1.ip8, actual_ht); + ret = host_cache.find((const uint8_t*) ip_addr1.get_ip6_ptr(), actual_ht); CHECK(true == ret); ret = actual_ht->find_service(proto1, port1, actual_app_entry); @@ -141,7 +152,7 @@ TEST(host_cache, host_cache_add_service_test) ret = host_cache_add_service(ip_addr2, proto2, port2, "tcp"); CHECK(true == ret); - ret = host_cache.find(ip_addr1.ip8, actual_ht); + ret = host_cache.find((const uint8_t*) ip_addr1.get_ip6_ptr(), actual_ht); CHECK(true == ret); ret = actual_ht->find_service(proto2, port2, actual_app_entry); @@ -153,10 +164,12 @@ TEST(host_cache, host_cache_add_service_test) int main(int argc, char** argv) { - sfip_t ip_addr1 = { 0x00de,0x10ad,{{0xbe,0xef,0xde,0xad,0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,0x34,0x56,0x78,0x90,0xab}} }; + SfIp ip_addr1; Protocol proto1 = 17; Port port1 = 443; + ip_addr1.pton(AF_INET6, "beef:dead:beef:abcd:ef01:2334:5678:90ab"); + // This is necessary to prevent the cpputest memory leak // detection from thinking there's a memory leak in the map // object contained within the global host_cache. The map diff --git a/src/host_tracker/test/host_tracker_module_test.cc b/src/host_tracker/test/host_tracker_module_test.cc index 1e24acc30..b3622448c 100644 --- a/src/host_tracker/test/host_tracker_module_test.cc +++ b/src/host_tracker/test/host_tracker_module_test.cc @@ -51,7 +51,7 @@ char* snort_strdup(const char* s) #define FRAG_POLICY 33 #define STREAM_POLICY 100 -sfip_t expected_addr; +SfIp expected_addr; TEST_GROUP(host_tracker_module) { @@ -127,16 +127,16 @@ TEST(host_tracker_module, host_tracker_module_test_basic) // Test that HostTrackerModule variables are set correctly. TEST(host_tracker_module, host_tracker_module_test_values) { - sfip_t cached_addr; + SfIp cached_addr; - HostIpKey host_ip_key(expected_addr.ip8); + HostIpKey host_ip_key((const uint8_t*) expected_addr.get_ip6_ptr()); std::shared_ptr ht; bool ret = host_cache.find(host_ip_key, ht); CHECK(ret == true); cached_addr = ht->get_ip_addr(); - CHECK(sfip_fast_equals_raw(&cached_addr, &expected_addr) == 1); + CHECK(cached_addr.fast_equals_raw(expected_addr) == true); Policy policy = ht->get_stream_policy(); CHECK(policy == STREAM_POLICY + 1); @@ -149,7 +149,7 @@ TEST(host_tracker_module, host_tracker_module_test_values) // Test that HostTrackerModule statistics are correct. TEST(host_tracker_module, host_tracker_module_test_stats) { - HostIpKey host_ip_key(expected_addr.ip8); + HostIpKey host_ip_key((const uint8_t*) expected_addr.get_ip6_ptr()); std::shared_ptr ht; bool ret = host_cache.find(host_ip_key, ht); diff --git a/src/host_tracker/test/host_tracker_test.cc b/src/host_tracker/test/host_tracker_test.cc index 5384b4580..60474b76c 100644 --- a/src/host_tracker/test/host_tracker_test.cc +++ b/src/host_tracker/test/host_tracker_test.cc @@ -24,6 +24,12 @@ #include #include +// Fake snort_strdup() because sfutil dependencies suck +char* snort_strdup(const char* str) +{ + return strdup(str); +} + TEST_GROUP(host_tracker) { }; @@ -32,15 +38,16 @@ TEST_GROUP(host_tracker) TEST(host_tracker, ipaddr_test) { HostTracker ht; - sfip_t zeroed_sfip; - sfip_t expected_ip_addr = { 0xde,0xad, {{0xbe,0xef,0xab,0xcd,0xef,0x01,0x23,}} }; - sfip_t actual_ip_addr; + SfIp zeroed_sfip; + SfIp expected_ip_addr; + SfIp actual_ip_addr; // Test IP prior to set. memset(&zeroed_sfip, 0, sizeof(zeroed_sfip)); actual_ip_addr = ht.get_ip_addr(); CHECK(0 == memcmp(&zeroed_sfip, &actual_ip_addr, sizeof(zeroed_sfip))); + expected_ip_addr.pton(AF_INET6, "beef:abcd:ef01:2300::"); ht.set_ip_addr(expected_ip_addr); actual_ip_addr = ht.get_ip_addr(); CHECK(0 == memcmp(&expected_ip_addr, &actual_ip_addr, sizeof(expected_ip_addr))); diff --git a/src/ips_options/ips_byte_extract.cc b/src/ips_options/ips_byte_extract.cc index 516dac845..1289e6485 100644 --- a/src/ips_options/ips_byte_extract.cc +++ b/src/ips_options/ips_byte_extract.cc @@ -36,6 +36,7 @@ #include "framework/cursor.h" #include "framework/parameter.h" #include "framework/module.h" +#include "utils/util.h" static THREAD_LOCAL ProfileStats byteExtractPerfStats; diff --git a/src/ips_options/ips_detection_filter.cc b/src/ips_options/ips_detection_filter.cc index 0e96e451e..9fd284eaa 100644 --- a/src/ips_options/ips_detection_filter.cc +++ b/src/ips_options/ips_detection_filter.cc @@ -20,25 +20,17 @@ // ips_detection_filter.cc author Russ Combs // FIXIT-L add DetectionFilterOption::eval() instead of special case -#include - #ifdef HAVE_CONFIG_H #include "config.h" #endif -#include -#include -#include "main/snort_types.h" -#include "main/snort_config.h" -#include "main/snort_debug.h" -#include "utils/util.h" #include "detection/treenodes.h" -#include "detection/detection_defines.h" -#include "framework/ips_option.h" -#include "framework/parameter.h" -#include "framework/module.h" #include "filters/detection_filter.h" #include "filters/sfthd.h" +#include "framework/decode_data.h" +#include "framework/ips_option.h" +#include "framework/module.h" +#include "main/snort_config.h" #define s_name "detection_filter" diff --git a/src/ips_options/ips_metadata.cc b/src/ips_options/ips_metadata.cc index 9524101f4..ef66d2244 100644 --- a/src/ips_options/ips_metadata.cc +++ b/src/ips_options/ips_metadata.cc @@ -21,19 +21,11 @@ #include "config.h" #endif -#include -#include - -#include "log/messages.h" -#include "main/snort_types.h" -#include "main/snort_debug.h" -#include "main/snort_config.h" -#include "detection/detection_defines.h" +#include "framework/decode_data.h" #include "framework/ips_option.h" -#include "framework/parameter.h" #include "framework/module.h" +#include "log/messages.h" #include "parser/parse_conf.h" -#include "parser/parser.h" using namespace std; diff --git a/src/ips_options/ips_reference.cc b/src/ips_options/ips_reference.cc index f76ebeb69..c9f192778 100644 --- a/src/ips_options/ips_reference.cc +++ b/src/ips_options/ips_reference.cc @@ -21,15 +21,9 @@ #include "config.h" #endif -#include - -#include "main/snort_types.h" -#include "main/snort_debug.h" -#include "main/snort_config.h" #include "detection/treenodes.h" -#include "detection/detection_defines.h" +#include "framework/decode_data.h" #include "framework/ips_option.h" -#include "framework/parameter.h" #include "framework/module.h" #define s_name "reference" diff --git a/src/ips_options/ips_sd_pattern.cc b/src/ips_options/ips_sd_pattern.cc index 33575598e..4b2cf6baf 100644 --- a/src/ips_options/ips_sd_pattern.cc +++ b/src/ips_options/ips_sd_pattern.cc @@ -39,6 +39,8 @@ #include "main/thread.h" #include "parser/parser.h" #include "profiler/profiler.h" +#include "protocols/packet.h" + #include "sd_credit_card.h" #define s_name "sd_pattern" diff --git a/src/ips_options/ips_session.cc b/src/ips_options/ips_session.cc index 97ad6878e..ccf031815 100644 --- a/src/ips_options/ips_session.cc +++ b/src/ips_options/ips_session.cc @@ -170,7 +170,7 @@ static FILE* OpenSessionFile(Packet* p) { char filename[STD_BUF]; char session_file[STD_BUF]; /* name of session file */ - const sfip_t* dst, * src; + const SfIp* dst, * src; FILE* ret; @@ -187,39 +187,39 @@ static FILE* OpenSessionFile(Packet* p) const char* addr; - if (sfip_contains(&snort_conf->homenet, dst) == SFIP_CONTAINS) + if (snort_conf->homenet.contains(dst) == SFIP_CONTAINS) { - if (sfip_contains(&snort_conf->homenet, src) == SFIP_NOT_CONTAINS) + if (snort_conf->homenet.contains(src) == SFIP_NOT_CONTAINS) { - addr = inet_ntoa(p->ptrs.ip_api.get_src()); + addr = p->ptrs.ip_api.get_src()->ntoa(); } else { if (p->ptrs.sp >= p->ptrs.dp) { - addr = inet_ntoa(p->ptrs.ip_api.get_src()); + addr = p->ptrs.ip_api.get_src()->ntoa(); } else { - addr = inet_ntoa(p->ptrs.ip_api.get_dst()); + addr = p->ptrs.ip_api.get_dst()->ntoa(); } } } else { - if (sfip_contains(&snort_conf->homenet, src) == SFIP_CONTAINS) + if (snort_conf->homenet.contains(src) == SFIP_CONTAINS) { - addr = inet_ntoa(p->ptrs.ip_api.get_dst()); + addr = p->ptrs.ip_api.get_dst()->ntoa(); } else { if (p->ptrs.sp >= p->ptrs.dp) { - addr = inet_ntoa(p->ptrs.ip_api.get_src()); + addr = p->ptrs.ip_api.get_src()->ntoa(); } else { - addr = inet_ntoa(p->ptrs.ip_api.get_dst()); + addr = p->ptrs.ip_api.get_dst()->ntoa(); } } } diff --git a/src/ips_options/test/Makefile.am b/src/ips_options/test/Makefile.am index 5702ead20..cf36e1370 100644 --- a/src/ips_options/test/Makefile.am +++ b/src/ips_options/test/Makefile.am @@ -16,6 +16,7 @@ ips_regex_test_LDADD = \ ../../framework/module.o \ ../../framework/value.o \ ../../sfip/sf_ip.o \ +../../sfip/sf_cidr.o \ @CPPUTEST_LDFLAGS@ endif diff --git a/src/latency/rule_latency.cc b/src/latency/rule_latency.cc index 16c0cf2d5..3c0917707 100644 --- a/src/latency/rule_latency.cc +++ b/src/latency/rule_latency.cc @@ -33,6 +33,7 @@ #include "events/event_queue.h" #include "log/messages.h" #include "main/snort_config.h" +#include "protocols/packet.h" #include "sfip/sf_ip.h" #include "utils/stats.h" diff --git a/src/log/log.cc b/src/log/log.cc index 0fce4c62e..8cc6b0d98 100644 --- a/src/log/log.cc +++ b/src/log/log.cc @@ -36,6 +36,7 @@ #include "main/snort_debug.h" #include "main/snort_config.h" #include "protocols/tcp.h" +#include "utils/util.h" #include "log_text.h" #include "messages.h" diff --git a/src/log/log_text.cc b/src/log/log_text.cc index 6e8c2cc96..224421aed 100644 --- a/src/log/log_text.cc +++ b/src/log/log_text.cc @@ -26,50 +26,28 @@ #include "config.h" #endif -#include -#include -#include -#include -#include - extern "C" { #include } -#include "log.h" -#include "text_log.h" -#include "obfuscator.h" - -#include "detection/rules.h" -#include "detection/treenodes.h" -#include "detection/signature.h" #include "detection/detection_util.h" #include "log/messages.h" -#include "main/snort_debug.h" #include "main/snort_config.h" #include "packet_io/sfdaq.h" - -#include "sfip/sf_ip.h" -#include "utils/util.h" -#include "utils/util_net.h" - -#include "protocols/packet.h" -#include "protocols/layer.h" #include "protocols/eth.h" -#include "protocols/ipv4.h" -#include "protocols/ipv6.h" -#include "protocols/icmp6.h" -#include "protocols/icmp4.h" -#include "protocols/udp.h" -#include "protocols/tcp.h" #include "protocols/gre.h" -#include "protocols/token_ring.h" -#include "protocols/wlan.h" -#include "protocols/linux_sll.h" -#include "protocols/eapol.h" +#include "protocols/icmp4.h" #include "protocols/ipv4_options.h" -#include "protocols/tcp_options.h" #include "protocols/packet_manager.h" +#include "protocols/tcp.h" +#include "protocols/tcp_options.h" +#include "protocols/udp.h" +#include "utils/util.h" +#include "utils/util_net.h" + +#include "log.h" +#include "obfuscator.h" +#include "text_log.h" /*-------------------------------------------------------------------- * utility functions @@ -1021,13 +999,13 @@ void LogICMPHeader(TextLog* log, Packet* p) } /* written this way since inet_ntoa was typedef'ed to use sfip_ntoa -* which requires sfip_t instead of inaddr's. This call to inet_ntoa -* is a rare case that doesn't use sfip_t's. */ +* which requires SfIp instead of inaddr's. This call to inet_ntoa +* is a rare case that doesn't use SfIp's. */ // XXX-IPv6 NOT YET IMPLEMENTED - IPV6 addresses technically not supported - need to change ICMP /* no inet_ntop in Windows */ - sfip_raw_ntop(AF_INET, (const void*)(&p->ptrs.icmph->s_icmp_gwaddr.s_addr), + snort_inet_ntop(AF_INET, (const void*)(&p->ptrs.icmph->s_icmp_gwaddr.s_addr), buf, sizeof(buf)); TextLog_Print(log, " NEW GW: %s", buf); diff --git a/src/log/log_text.h b/src/log/log_text.h index df797e593..b802dd8cc 100644 --- a/src/log/log_text.h +++ b/src/log/log_text.h @@ -24,9 +24,7 @@ // Use these methods to write to a TextLog -#include #include "log/text_log.h" -#include "main/snort_types.h" struct Packet; struct Event; diff --git a/src/log/messages.cc b/src/log/messages.cc index 1d5de9f51..2eb74647c 100644 --- a/src/log/messages.cc +++ b/src/log/messages.cc @@ -49,6 +49,7 @@ #include "time/packet_time.h" #include "time/timersub.h" #include "sfip/sf_ip.h" +#include "utils/util.h" #ifdef UNIT_TEST #include "catch/catch.hpp" @@ -451,7 +452,7 @@ void PrintPacketData(const uint8_t* data, const uint32_t len) LogMessage("\n"); } -char* ObfuscateIpToText(const sfip_t* ip) +char* ObfuscateIpToText(const SfIp* ip) { static THREAD_LOCAL char ip_buf1[INET6_ADDRSTRLEN]; static THREAD_LOCAL char ip_buf2[INET6_ADDRSTRLEN]; @@ -470,7 +471,7 @@ char* ObfuscateIpToText(const sfip_t* ip) if (ip == NULL) return ip_buf; - if (!sfip_is_set(snort_conf->obfuscation_net)) + if (!snort_conf->obfuscation_net.is_set()) { if (ip->is_ip6()) SnortSnprintf(ip_buf, buf_size, "x:x:x:x::x:x:x:x"); @@ -479,22 +480,22 @@ char* ObfuscateIpToText(const sfip_t* ip) } else { - sfip_t tmp; - char* tmp_buf; + SfIp tmp; + const char* tmp_buf; - sfip_copy(tmp, ip); + tmp.set(*ip); - if (sfip_is_set(snort_conf->homenet)) + if (snort_conf->homenet.is_set()) { - if (sfip_contains(&snort_conf->homenet, &tmp) == SFIP_CONTAINS) - sfip_obfuscate(&snort_conf->obfuscation_net, &tmp); + if (snort_conf->homenet.contains(&tmp) == SFIP_CONTAINS) + tmp.obfuscate(&snort_conf->obfuscation_net); } else { - sfip_obfuscate(&snort_conf->obfuscation_net, &tmp); + tmp.obfuscate(&snort_conf->obfuscation_net); } - tmp_buf = sfip_to_str(&tmp); + tmp_buf = tmp.ntoa(); SnortSnprintf(ip_buf, buf_size, "%s", tmp_buf); } diff --git a/src/log/messages.h b/src/log/messages.h index 18867e3ef..3a09ff7d7 100644 --- a/src/log/messages.h +++ b/src/log/messages.h @@ -26,7 +26,6 @@ #endif #include "main/snort_types.h" -#include "sfip/sfip_t.h" #include @@ -90,7 +89,8 @@ private: SO_PUBLIC NORETURN void FatalError(const char*, ...) __attribute__((format (printf, 1, 2))); SO_PUBLIC void PrintPacketData(const uint8_t*, const uint32_t); -SO_PUBLIC char* ObfuscateIpToText(const sfip_t*); +struct SfIp; +SO_PUBLIC char* ObfuscateIpToText(const SfIp*); void log_safec_error(const char*, void*, int); diff --git a/src/loggers/alert_csv.cc b/src/loggers/alert_csv.cc index 6f6123bce..64c6cfc75 100644 --- a/src/loggers/alert_csv.cc +++ b/src/loggers/alert_csv.cc @@ -104,7 +104,7 @@ static void ff_dgm_len(Args& a) static void ff_dst_addr(Args& a) { if ( a.pkt->has_ip() or a.pkt->is_data() ) - TextLog_Puts(csv_log, inet_ntoa(a.pkt->ptrs.ip_api.get_dst())); + TextLog_Puts(csv_log, a.pkt->ptrs.ip_api.get_dst()->ntoa()); } static void ff_dst_ap(Args& a) @@ -113,7 +113,7 @@ static void ff_dst_ap(Args& a) unsigned port = 0; if ( a.pkt->has_ip() or a.pkt->is_data() ) - addr = sfip_to_str(a.pkt->ptrs.ip_api.get_dst()); + addr = a.pkt->ptrs.ip_api.get_dst()->ntoa(); if ( a.pkt->proto_bits & (PROTO_BIT__TCP|PROTO_BIT__UDP) ) port = a.pkt->ptrs.dp; @@ -256,7 +256,7 @@ static void ff_sid(Args& a) static void ff_src_addr(Args& a) { if ( a.pkt->has_ip() or a.pkt->is_data() ) - TextLog_Puts(csv_log, inet_ntoa(a.pkt->ptrs.ip_api.get_src())); + TextLog_Puts(csv_log, a.pkt->ptrs.ip_api.get_src()->ntoa()); } static void ff_src_ap(Args& a) @@ -265,7 +265,7 @@ static void ff_src_ap(Args& a) unsigned port = 0; if ( a.pkt->has_ip() or a.pkt->is_data() ) - addr = sfip_to_str(a.pkt->ptrs.ip_api.get_src()); + addr = a.pkt->ptrs.ip_api.get_src()->ntoa(); if ( a.pkt->proto_bits & (PROTO_BIT__TCP|PROTO_BIT__UDP) ) port = a.pkt->ptrs.sp; diff --git a/src/loggers/alert_sf_socket.cc b/src/loggers/alert_sf_socket.cc index 549302722..5d6bb1830 100644 --- a/src/loggers/alert_sf_socket.cc +++ b/src/loggers/alert_sf_socket.cc @@ -45,6 +45,7 @@ #include "events/event.h" #include "hash/sfghash.h" #include "parser/parser.h" +#include "protocols/packet.h" #include "target_based/snort_protocols.h" #include "utils/util.h" @@ -311,8 +312,8 @@ static void load_sar(Packet* packet, Event* event, SnortActionRequest& sar) // 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()->ip32[0]); - sar.dest_ip = ntohl(packet->ptrs.ip_api.get_dst()->ip32[0]); + 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()) diff --git a/src/loggers/log_hext.cc b/src/loggers/log_hext.cc index cd8c63b68..aa91e8ef1 100644 --- a/src/loggers/log_hext.cc +++ b/src/loggers/log_hext.cc @@ -61,7 +61,7 @@ static void log_header(const Packet* p) char src[INET6_ADDRSTRLEN]; char dst[INET6_ADDRSTRLEN]; - const sfip_t* addr = p->ptrs.ip_api.get_src(); + const SfIp* addr = p->ptrs.ip_api.get_src(); sfip_ntop(addr, src, sizeof(src)); addr = p->ptrs.ip_api.get_dst(); diff --git a/src/loggers/unified2.cc b/src/loggers/unified2.cc index 5b137c44a..e3056ac73 100644 --- a/src/loggers/unified2.cc +++ b/src/loggers/unified2.cc @@ -336,13 +336,13 @@ static void _AlertIP6_v2(Packet* p, const char*, Unified2Config* config, Event* if(p->ptrs.ip_api.is_ip()) { - const sfip_t* ip; + const SfIp* ip; ip = p->ptrs.ip_api.get_src(); - alertdata.ip_source = *(struct in6_addr*)ip->ip32; + alertdata.ip_source = *(struct in6_addr*)ip->get_ip6_ptr(); ip = p->ptrs.ip_api.get_dst(); - alertdata.ip_destination = *(struct in6_addr*)ip->ip32; + alertdata.ip_destination = *(struct in6_addr*)ip->get_ip6_ptr(); if (p->is_portscan()) { @@ -897,12 +897,12 @@ void U2Logger::alert(Packet* p, const char* msg, Event* event) // FIXIT-M delete ip6 extra data; support ip6 normally if (SnortConfig::get_log_ip6_extra() && p->ptrs.ip_api.is_ip6()) { - const sfip_t* ip = p->ptrs.ip_api.get_src(); + const SfIp* ip = p->ptrs.ip_api.get_src(); _WriteExtraData(&config, event->event_id, event->ref_time.tv_sec, - &ip->ip8[0], sizeof(struct in6_addr), EVENT_INFO_IPV6_SRC); + (const uint8_t*) ip->get_ip6_ptr(), sizeof(struct in6_addr), EVENT_INFO_IPV6_SRC); ip = p->ptrs.ip_api.get_dst(); _WriteExtraData(&config, event->event_id, event->ref_time.tv_sec, - &ip->ip8[0], sizeof(struct in6_addr), EVENT_INFO_IPV6_DST); + (const uint8_t*) ip->get_ip6_ptr(), sizeof(struct in6_addr), EVENT_INFO_IPV6_DST); } } else // ip4 or data diff --git a/src/main.cc b/src/main.cc index 879c37051..b10489b56 100644 --- a/src/main.cc +++ b/src/main.cc @@ -117,7 +117,7 @@ void main_poke(unsigned id) pig_poke->put(id); } -int main_read() +static int main_read() { std::lock_guard lock(poke_mutex); return pig_poke->get(-1); diff --git a/src/main/modules.cc b/src/main/modules.cc index 639e1d3e3..8d948bfea 100644 --- a/src/main/modules.cc +++ b/src/main/modules.cc @@ -665,7 +665,7 @@ bool AlertsModule::set(const char*, Value& v, SnortConfig* sc) sc->rate_filter_config->memcap = v.get_long(); else if ( v.is("reference_net") ) - return ( sfip_pton(v.get_string(), &sc->homenet) == SFIP_SUCCESS ); + return ( sc->homenet.set(v.get_string()) == SFIP_SUCCESS ); else if ( v.is("stateful") ) v.update_mask(sc->run_flags, RUN_FLAG__ASSURE_EST); diff --git a/src/main/snort_config.cc b/src/main/snort_config.cc index 24894dc1d..bc9e43642 100644 --- a/src/main/snort_config.cc +++ b/src/main/snort_config.cc @@ -45,7 +45,7 @@ #include "sfip/sf_ip.h" #include "thread_config.h" #include "target_based/sftarget_reader.h" -#include "target_based/snort_protocols.h" +#include "utils/util.h" #ifdef HAVE_HYPERSCAN #include "ips_options/ips_regex.h" @@ -177,8 +177,8 @@ SnortConfig::SnortConfig() thread_config = new ThreadConfig(); - sfip_clear(homenet); - sfip_clear(obfuscation_net); + homenet.clear(); + obfuscation_net.clear(); memset(evalOrder, 0, sizeof(evalOrder)); proto_ref = new ProtocolReference; @@ -333,11 +333,11 @@ void SnortConfig::merge(SnortConfig* cmd_line) if (cmd_line->max_ip_layers != 0) max_ip_layers = cmd_line->max_ip_layers; - if (cmd_line->obfuscation_net.family != 0) - memcpy(&obfuscation_net, &cmd_line->obfuscation_net, sizeof(sfip_t)); + if (cmd_line->obfuscation_net.get_family() != 0) + memcpy(&obfuscation_net, &cmd_line->obfuscation_net, sizeof(obfuscation_net)); - if (cmd_line->homenet.family != 0) - memcpy(&homenet, &cmd_line->homenet, sizeof(sfip_t)); + if (cmd_line->homenet.get_family() != 0) + memcpy(&homenet, &cmd_line->homenet, sizeof(homenet)); if ( !cmd_line->bpf_file.empty() ) bpf_file = cmd_line->bpf_file; diff --git a/src/main/snort_config.h b/src/main/snort_config.h index 0cba7b8d0..62a262c2f 100644 --- a/src/main/snort_config.h +++ b/src/main/snort_config.h @@ -27,18 +27,12 @@ #include "config.h" #endif -#include -#include -#include -#include - -#include "sfip/sfip_t.h" -#include "main/policy.h" -#include "utils/util.h" -#include "protocols/packet.h" -#include "framework/bits.h" #include "events/event_queue.h" #include "file_api/file_config.h" +#include "framework/bits.h" +#include "main/policy.h" +#include "main/thread.h" +#include "sfip/sf_cidr.h" #define DEFAULT_LOG_DIR "." @@ -165,7 +159,7 @@ public: // alert module stuff bool default_rule_state = true; - sfip_t homenet; + SfCidr homenet; //------------------------------------------------------ // output module stuff @@ -264,7 +258,7 @@ public: // FIXIT-L command line only stuff, add to conf / module uint32_t event_log_id = 0; - sfip_t obfuscation_net; + SfCidr obfuscation_net; std::string bpf_filter; //------------------------------------------------------ diff --git a/src/main/thread.cc b/src/main/thread.cc index 46a06400c..cb441500f 100644 --- a/src/main/thread.cc +++ b/src/main/thread.cc @@ -19,6 +19,8 @@ #include "thread.h" +#include + #include "snort_config.h" #include "thread_config.h" diff --git a/src/managers/connector_manager.cc b/src/managers/connector_manager.cc index 79794fc0e..e37981fa0 100644 --- a/src/managers/connector_manager.cc +++ b/src/managers/connector_manager.cc @@ -20,6 +20,7 @@ #include "connector_manager.h" #include + #include #include #include @@ -28,6 +29,8 @@ #include "log/messages.h" #include "main/snort_config.h" #include "main/snort_debug.h" +#include "utils/util.h" + #include "module_manager.h" // ConnectorManager Private Data diff --git a/src/network_inspectors/appid/app_forecast.cc b/src/network_inspectors/appid/app_forecast.cc index 2313e6ea0..542cfc94c 100644 --- a/src/network_inspectors/appid/app_forecast.cc +++ b/src/network_inspectors/appid/app_forecast.cc @@ -84,10 +84,10 @@ void add_af_indicator(ApplicationId indicator, ApplicationId forecast, Applicati static inline void rekey_master_AF_key(Packet* p, int dir, ApplicationId forecast) { - const sfip_t* src = dir ? p->ptrs.ip_api.get_dst() : p->ptrs.ip_api.get_src(); + const SfIp* src = dir ? p->ptrs.ip_api.get_dst() : p->ptrs.ip_api.get_src(); for (int i = 0; i < 4; i++) - master_key.ip[i] = src->ip32[i]; + master_key.ip[i] = src->get_ip6_ptr()[i]; master_key.forecast = forecast; } diff --git a/src/network_inspectors/appid/appid_api.cc b/src/network_inspectors/appid/appid_api.cc index 199c61122..b0aa6f7d7 100644 --- a/src/network_inspectors/appid/appid_api.cc +++ b/src/network_inspectors/appid/appid_api.cc @@ -382,20 +382,6 @@ uint16_t AppIdApi::get_http_cookie_end_offset(AppIdSession* asd) return 0; } -uint16_t getHttpFieldOffset(AppIdSession* asd, HTTP_FIELD_ID fieldId) -{ - if (asd && asd->hsession && fieldId >= 0 && fieldId <= HTTP_FIELD_MAX) - return asd->hsession->fieldOffset[fieldId]; - return 0; -} - -uint16_t getHttpFieldEndOffset(AppIdSession* asd, HTTP_FIELD_ID fieldId) -{ - if (asd && asd->hsession && fieldId >= 0 && fieldId <= HTTP_FIELD_MAX) - return asd->hsession->fieldEndOffset[fieldId]; - return 0; -} - SEARCH_SUPPORT_TYPE AppIdApi::get_http_search(AppIdSession* asd) { if (asd) @@ -404,7 +390,7 @@ SEARCH_SUPPORT_TYPE AppIdApi::get_http_search(AppIdSession* asd) return NOT_A_SEARCH_ENGINE; } -sfip_t* AppIdApi::get_http_xff_addr(AppIdSession* asd) +SfIp* AppIdApi::get_http_xff_addr(AppIdSession* asd) { if (asd && asd->hsession) return asd->hsession->xffAddr; @@ -418,14 +404,14 @@ char* AppIdApi::get_tls_host(AppIdSession* asd) return nullptr; } -sfip_t* AppIdApi::get_service_ip(AppIdSession* asd) +SfIp* AppIdApi::get_service_ip(AppIdSession* asd) { if (asd) return &asd->service_ip; return nullptr; } -sfip_t* AppIdApi::get_initiator_ip(AppIdSession* asd) +SfIp* AppIdApi::get_initiator_ip(AppIdSession* asd) { return asd ? &asd->common.initiator_ip : nullptr; } @@ -533,7 +519,7 @@ uint32_t AppIdApi::produce_ha_state(Flow* flow, uint8_t* buf) } uint32_t AppIdApi::consume_ha_state(Flow* flow, const uint8_t* buf, uint8_t, IpProtocol proto, - sfip_t* ip, uint16_t port) + SfIp* ip, uint16_t port) { AppIdSessionHA* appHA = (AppIdSessionHA*)buf; if (appHA->flags & APPID_HA_FLAGS_APP) diff --git a/src/network_inspectors/appid/appid_api.h b/src/network_inspectors/appid/appid_api.h index 943b8612b..4694fc11f 100644 --- a/src/network_inspectors/appid/appid_api.h +++ b/src/network_inspectors/appid/appid_api.h @@ -175,7 +175,7 @@ enum HTTP_FIELD_ID // AppId API // ----------------------------------------------------------------------------- -struct sfip_t; +struct SfIp; class SO_PUBLIC AppIdApi { @@ -206,8 +206,8 @@ public: APPID_FLOW_TYPE get_flow_type(AppIdSession*); void get_service_info(AppIdSession*, char **serviceVendor, char** serviceVersion, RNAServiceSubtype** subtype); short get_service_port(AppIdSession*); - sfip_t* get_service_ip(AppIdSession*); - sfip_t* get_initiator_ip(AppIdSession*); + SfIp* get_service_ip(AppIdSession*); + SfIp* get_initiator_ip(AppIdSession*); char* get_http_user_agent(AppIdSession*); char* get_http_host(AppIdSession*); char* get_http_url(AppIdSession*); @@ -226,7 +226,7 @@ public: uint16_t get_http_cookie_offset(AppIdSession*); uint16_t get_http_cookie_end_offset(AppIdSession*); SEARCH_SUPPORT_TYPE get_http_search(AppIdSession*); - sfip_t* get_http_xff_addr(AppIdSession*); + SfIp* get_http_xff_addr(AppIdSession*); char* get_tls_host(AppIdSession*); DHCPData* get_dhcp_fp_data(AppIdSession*); void free_dhcp_fp_data(AppIdSession*, DHCPData*); @@ -237,7 +237,7 @@ public: char* get_netbios_name(AppIdSession*); uint32_t produce_ha_state(Flow* flow, uint8_t* buf); uint32_t consume_ha_state(Flow* flow, const uint8_t* buf, uint8_t length, IpProtocol proto, - sfip_t* ip, uint16_t initiatorPort); + SfIp* ip, uint16_t initiatorPort); AppIdSession* get_appid_data(Flow* flow); char* get_dns_query(AppIdSession*, uint8_t* query_len); uint16_t get_dns_query_offset(AppIdSession*); diff --git a/src/network_inspectors/appid/appid_config.h b/src/network_inspectors/appid/appid_config.h index b2d8510d4..196c33b4b 100644 --- a/src/network_inspectors/appid/appid_config.h +++ b/src/network_inspectors/appid/appid_config.h @@ -72,9 +72,9 @@ struct AppIdSessionLogFilter dip.clear(); } - sfip_t sip; + SfIp sip; bool sip_flag = false; - sfip_t dip; + SfIp dip; bool dip_flag = false; uint16_t sport = 0; uint16_t dport = 0; diff --git a/src/network_inspectors/appid/appid_inspector.cc b/src/network_inspectors/appid/appid_inspector.cc index 5d0112812..c774f083d 100644 --- a/src/network_inspectors/appid/appid_inspector.cc +++ b/src/network_inspectors/appid/appid_inspector.cc @@ -60,7 +60,7 @@ static void dump_appid_stats() // FIXIT-L - appid cleans up openssl now as it is the primary (only) user... eventually this // should probably be done outside of appid -void openssl_cleanup() +static void openssl_cleanup() { CRYPTO_cleanup_all_ex_data(); } diff --git a/src/network_inspectors/appid/appid_module.cc b/src/network_inspectors/appid/appid_module.cc index 8c41f4f28..9b15a49f3 100644 --- a/src/network_inspectors/appid/appid_module.cc +++ b/src/network_inspectors/appid/appid_module.cc @@ -217,9 +217,9 @@ bool AppIdModule::set(const char*, Value& v, SnortConfig*) else if ( v.is("log_all_sessions") ) config->session_log_filter.log_all_sessions = v.get_bool(); else if (v.is("src_ip") ) - sfip_pton(v.get_string(), &config->session_log_filter.sip); + config->session_log_filter.sip.set(v.get_string()); else if (v.is("dst_ip") ) - sfip_pton(v.get_string(), &config->session_log_filter.dip); + config->session_log_filter.dip.set(v.get_string()); else return false; diff --git a/src/network_inspectors/appid/appid_session.cc b/src/network_inspectors/appid/appid_session.cc index 6625a98ae..836045f10 100644 --- a/src/network_inspectors/appid/appid_session.cc +++ b/src/network_inspectors/appid/appid_session.cc @@ -111,10 +111,10 @@ void AppIdSession::set_session_logging_state(const Packet* pkt, int direction) } else { - if( !sfip_equals( pkt->ptrs.ip_api.get_src(), &config->mod_config->session_log_filter.sip) ) + if( !pkt->ptrs.ip_api.get_src()->equals(config->mod_config->session_log_filter.sip) ) return; - if( !sfip_equals( pkt->ptrs.ip_api.get_dst(), &config->mod_config->session_log_filter.dip) ) + if( !pkt->ptrs.ip_api.get_dst()->equals(config->mod_config->session_log_filter.dip) ) return; if( !( pkt->ptrs.dp == config->mod_config->session_log_filter.dport ) ) @@ -130,9 +130,9 @@ void AppIdSession::set_session_logging_state(const Packet* pkt, int direction) } if(session_logging_enabled) - snprintf(session_logging_id, MAX_SESSION_LOGGING_ID_LEN, "%s-%u -> %s-%u %u%s AS %u I %u", - sfip_to_str(pkt->ptrs.ip_api.get_src()), (unsigned)pkt->ptrs.sp, - sfip_to_str(pkt->ptrs.ip_api.get_dst()), (unsigned)pkt->ptrs.dp, + snprintf(session_logging_id, MAX_SESSION_LOGGING_ID_LEN, "%s-%hu -> %s-%hu %u%s AS %u I %u", + pkt->ptrs.ip_api.get_src()->ntoa(), pkt->ptrs.sp, + pkt->ptrs.ip_api.get_dst()->ntoa(), pkt->ptrs.dp, (unsigned)pkt->ptrs.type, (direction == APP_ID_FROM_INITIATOR) ? "" : " R", (unsigned)pkt->pkth->address_space_id, get_instance_id()); @@ -143,7 +143,7 @@ AppIdSession* AppIdSession::allocate_session(const Packet* p, IpProtocol proto, { uint16_t port = 0; - const sfip_t* ip = (direction == APP_ID_FROM_INITIATOR) + const SfIp* ip = (direction == APP_ID_FROM_INITIATOR) ? p->ptrs.ip_api.get_src() : p->ptrs.ip_api.get_dst(); if ( ( proto == IpProtocol::TCP || proto == IpProtocol::UDP ) && ( p->ptrs.sp != p->ptrs.dp ) ) port = (direction == APP_ID_FROM_INITIATOR) ? p->ptrs.sp : p->ptrs.dp; @@ -158,7 +158,7 @@ AppIdSession* AppIdSession::allocate_session(const Packet* p, IpProtocol proto, return data; } -AppIdSession::AppIdSession(IpProtocol proto, const sfip_t* ip, uint16_t port) +AppIdSession::AppIdSession(IpProtocol proto, const SfIp* ip, uint16_t port) : FlowData(flow_id), protocol(proto) { service_ip.clear(); @@ -210,8 +210,8 @@ static inline PktType get_pkt_type_from_ip_proto(IpProtocol proto) return PktType::NONE; } -AppIdSession* AppIdSession::create_future_session(const Packet* ctrlPkt, const sfip_t* cliIp, uint16_t cliPort, - const sfip_t* srvIp, uint16_t srvPort, IpProtocol proto, int16_t app_id, int /*flags*/) +AppIdSession* AppIdSession::create_future_session(const Packet* ctrlPkt, const SfIp* cliIp, uint16_t cliPort, + const SfIp* srvIp, uint16_t srvPort, IpProtocol proto, int16_t app_id, int /*flags*/) { char src_ip[INET6_ADDRSTRLEN]; char dst_ip[INET6_ADDRSTRLEN]; @@ -972,7 +972,7 @@ void AppIdSession::checkTerminateTpModule(uint16_t tpPktCount) } } -bool AppIdSession::do_third_party_discovery(IpProtocol protocol, const sfip_t* ip, +bool AppIdSession::do_third_party_discovery(IpProtocol protocol, const SfIp* ip, Packet* p, int& direction) { ThirdPartyAppIDAttributeData* tp_attribute_data; @@ -1212,26 +1212,25 @@ void AppIdSession::pickHttpXffAddress(Packet*, ThirdPartyAppIDAttributeData* att for (j = 0; j < attribute_data->numXffFields; j++) { if (hsession->xffAddr) - sfip_free(hsession->xffAddr); + { + delete hsession->xffAddr; + hsession->xffAddr = nullptr; + } if (strncasecmp(attribute_data->xffFieldValue[j].field, hsession->xffPrecedence[i], UINT8_MAX) == 0) { char* tmp = strchr(attribute_data->xffFieldValue[j].value, ','); - SFIP_RET status; - if (!tmp) - { - hsession->xffAddr = sfip_alloc( - attribute_data->xffFieldValue[j].value, &status); - } // For a comma-separated list of addresses, pick the first address - else - { + if (tmp) attribute_data->xffFieldValue[j].value[tmp - - attribute_data->xffFieldValue[j].value] = '\0'; - hsession->xffAddr = sfip_alloc( - attribute_data->xffFieldValue[j].value, &status); + attribute_data->xffFieldValue[j].value] = '\0'; + hsession->xffAddr = new SfIp(); + if (hsession->xffAddr->set(attribute_data->xffFieldValue[j].value) != SFIP_SUCCESS) + { + delete hsession->xffAddr; + hsession->xffAddr = nullptr; } break; } @@ -1481,7 +1480,7 @@ void AppIdSession::do_application_discovery(Packet* p) AppId payload_app_id = 0; bool isTpAppidDiscoveryDone = false; int direction = 0; - const sfip_t* ip = nullptr; + const SfIp* ip = nullptr; if( is_packet_ignored(p) ) return; @@ -1507,7 +1506,7 @@ void AppIdSession::do_application_discovery(Packet* p) direction = (asd->common.initiator_port == p->ptrs.sp) ? APP_ID_FROM_INITIATOR : APP_ID_FROM_RESPONDER; else - direction = (sfip_fast_equals_raw(ip, &asd->common.initiator_ip)) ? + direction = ip->fast_equals_raw(asd->common.initiator_ip) ? APP_ID_FROM_INITIATOR : APP_ID_FROM_RESPONDER; asd->in_expected_cache = false; @@ -1609,7 +1608,7 @@ void AppIdSession::do_application_discovery(Packet* p) if ( tcph->is_rst() && asd->previous_tcp_flags == TH_SYN ) { asd->set_session_flags(APPID_SESSION_SYN_RST); - if (sfip_is_set(&asd->service_ip)) + if (asd->service_ip.is_set()) { ip = &asd->service_ip; port = asd->service_port; @@ -1869,9 +1868,9 @@ void AppIdSession::do_application_discovery(Packet* p) } } -static inline int PENetworkMatch(const sfip_t* pktAddr, const PortExclusion* pe) +static inline int PENetworkMatch(const SfIp* pktAddr, const PortExclusion* pe) { - const uint32_t* pkt = pktAddr->ip32; + const uint32_t* pkt = pktAddr->get_ip6_ptr(); const uint32_t* nm = pe->netmask.u6_addr32; const uint32_t* peIP = pe->ip.u6_addr32; return (((pkt[0] & nm[0]) == peIP[0]) @@ -1886,7 +1885,7 @@ static inline int check_port_exclusion(const Packet* pkt, bool reversed) AppIdPortExclusions* dst_port_exclusions; SF_LIST* pe_list; PortExclusion* pe; - const sfip_t* s_ip; + const SfIp* s_ip; AppIdConfig* config = AppIdConfig::get_appid_config(); if ( pkt->is_tcp() ) @@ -1942,7 +1941,7 @@ static inline int check_port_exclusion(const Packet* pkt, bool reversed) static inline unsigned get_ipfuncs_flags(const Packet* p, bool dst) { - const sfip_t* sf_ip; + const SfIp* sf_ip; NetworkSet* net_list; unsigned flags; int32_t zone; @@ -1970,13 +1969,13 @@ static inline unsigned get_ipfuncs_flags(const Packet* p, bool dst) if ( sf_ip->is_ip4() ) { - if (sf_ip->ip32[0] == 0xFFFFFFFF) + if (sf_ip->get_ip4_value() == 0xFFFFFFFF) return IPFUNCS_CHECKED; - NetworkSetManager::contains_ex(net_list, ntohl(sf_ip->ip32[0]), &flags); + NetworkSetManager::contains_ex(net_list, ntohl(sf_ip->get_ip4_value()), &flags); } else { - memcpy(&ip6, sf_ip->ip32, sizeof(ip6)); + memcpy(&ip6, sf_ip->get_ip6_ptr(), sizeof(ip6)); NetworkSetManager::ntoh_ipv6(&ip6); NetworkSetManager::contains6_ex(net_list, &ip6, &flags); } @@ -2629,7 +2628,7 @@ void AppIdSession::clear_http_field() } if (hsession->xffAddr) { - sfip_free(hsession->xffAddr); + delete hsession->xffAddr; hsession->xffAddr = nullptr; } } diff --git a/src/network_inspectors/appid/appid_session.h b/src/network_inspectors/appid/appid_session.h index 25c132cc6..4dd2d18a1 100644 --- a/src/network_inspectors/appid/appid_session.h +++ b/src/network_inspectors/appid/appid_session.h @@ -120,7 +120,7 @@ struct CommonAppIdData unsigned policyId = 0; //flags shared with other preprocessor via session attributes. uint64_t flags = 0; - sfip_t initiator_ip; + SfIp initiator_ip; uint16_t initiator_port = 0; }; @@ -177,7 +177,7 @@ struct httpSession int num_scans = 0; int get_offsets_from_rebuilt = 0; bool skip_simple_detect = false; - sfip_t* xffAddr = nullptr; + SfIp* xffAddr = nullptr; const char** xffPrecedence = nullptr; int numXffFields = 0; int ptype_scan_counts[NUMBER_OF_PTYPES] = { 0 }; @@ -221,11 +221,11 @@ void map_app_names_to_snort_ids(); class AppIdSession : public FlowData { public: - AppIdSession(IpProtocol, const sfip_t*, uint16_t port); + AppIdSession(IpProtocol, const SfIp*, uint16_t port); ~AppIdSession(); static AppIdSession* allocate_session(const Packet*, IpProtocol, int); - static AppIdSession* create_future_session(const Packet*, const sfip_t*, uint16_t, const sfip_t*, + static AppIdSession* create_future_session(const Packet*, const SfIp*, uint16_t, const SfIp*, uint16_t, IpProtocol, int16_t, int); static void do_application_discovery(Packet*); static void add_user(AppIdSession*, const char* username, AppId, int success); @@ -237,7 +237,7 @@ public: AppIdFlowData* flowData = nullptr; AppInfoManager* app_info_mgr = nullptr; - sfip_t service_ip; + SfIp service_ip; uint16_t service_port = 0; IpProtocol protocol = IpProtocol::PROTO_NOT_SET; uint8_t previous_tcp_flags = 0; @@ -407,7 +407,7 @@ private: // FIXIT-M these are not needed until appid for snort3 supports 3rd party detectors (e.g. NAVL) void ProcessThirdPartyResults(Packet*, int, AppId*, ThirdPartyAppIDAttributeData*); void checkTerminateTpModule(uint16_t tpPktCount); - bool do_third_party_discovery(IpProtocol, const sfip_t*, Packet*, int&); + bool do_third_party_discovery(IpProtocol, const SfIp*, Packet*, int&); void pickHttpXffAddress(Packet*, ThirdPartyAppIDAttributeData*); #endif diff --git a/src/network_inspectors/appid/appid_utils/ip_funcs.h b/src/network_inspectors/appid/appid_utils/ip_funcs.h index e037dc080..75c95b9d0 100644 --- a/src/network_inspectors/appid/appid_utils/ip_funcs.h +++ b/src/network_inspectors/appid/appid_utils/ip_funcs.h @@ -24,6 +24,7 @@ #include #include "protocols/ipv6.h" +#include "sfip/sf_ip.h" #include "network_set.h" #define IPFUNCS_EXCEPT_IP 0x01 @@ -66,14 +67,14 @@ inline void copyIpv4ToIpv6Network(ip::snort_in6_addr* keyIp, const uint32_t ip) //these functions are needed since snort does not store IPv4 address in highest 4 bytes //of 16 byte ip. -inline void copySnortIpToIpv6Network(ip::snort_in6_addr* keyIp, const sfip_t* snortIp) +inline void copySnortIpToIpv6Network(ip::snort_in6_addr* keyIp, const SfIp* snortIp) { - memcpy(keyIp, snortIp->ip32, sizeof(*keyIp)); + memcpy(keyIp, snortIp->get_ip6_ptr(), sizeof(*keyIp)); } -inline int cmpSnortIpToHostKey(const ip::snort_in6_addr* keyIp, const sfip_t* snortIp) +inline int cmpSnortIpToHostKey(const ip::snort_in6_addr* keyIp, const SfIp* snortIp) { - return memcmp(keyIp, snortIp->ip32, sizeof(*keyIp)); + return memcmp(keyIp, snortIp->get_ip6_ptr(), sizeof(*keyIp)); } #endif diff --git a/src/network_inspectors/appid/detector_plugins/detector_sip.cc b/src/network_inspectors/appid/detector_plugins/detector_sip.cc index 6f4f98941..940ff432d 100644 --- a/src/network_inspectors/appid/detector_plugins/detector_sip.cc +++ b/src/network_inspectors/appid/detector_plugins/detector_sip.cc @@ -468,8 +468,8 @@ static int get_sip_client_app(void* patternMatcher, const char* pattern, uint32_ return 1; } -static void createRtpFlow(AppIdSession* asd, const Packet* pkt, const sfip_t* cliIp, - uint16_t cliPort, const sfip_t* srvIp, uint16_t srvPort, IpProtocol proto, int16_t app_id) +static void createRtpFlow(AppIdSession* asd, const Packet* pkt, const SfIp* cliIp, + uint16_t cliPort, const SfIp* srvIp, uint16_t srvPort, IpProtocol proto, int16_t app_id) { AppIdSession* fp, * fp2; @@ -517,9 +517,9 @@ static void addFutureRtpFlows(SipEvent& event, AppIdSession* asd) while( media_a && media_b ) { DebugFormat(DEBUG_SIP, "Adding future channels Source IP: %s Port: %hu\n", - sfip_to_str(media_a->get_address()), media_a->get_port()); + media_a->get_address()->ntoa(), media_a->get_port()); DebugFormat(DEBUG_SIP, "Adding future channels Destine IP: %s Port: %hu\n", - sfip_to_str(media_b->get_address()), media_b->get_port()); + media_b->get_address()->ntoa(), media_b->get_port()); createRtpFlow(asd, event.get_packet(), media_a->get_address(), media_a->get_port(), media_b->get_address(), media_b->get_port(), IpProtocol::UDP, APP_ID_RTP); @@ -728,7 +728,7 @@ void SipEventHandler::handle(DataEvent& event, Flow* flow) { char src_ip[INET6_ADDRSTRLEN]; char dst_ip[INET6_ADDRSTRLEN]; - const sfip_t* ip; + const SfIp* ip; src_ip[0] = 0; ip = p->ptrs.ip_api.get_src(); diff --git a/src/network_inspectors/appid/host_port_app_cache.cc b/src/network_inspectors/appid/host_port_app_cache.cc index fcc5301ec..017c4b9eb 100644 --- a/src/network_inspectors/appid/host_port_app_cache.cc +++ b/src/network_inspectors/appid/host_port_app_cache.cc @@ -27,6 +27,8 @@ #include "log/messages.h" #include "sfip/sf_ip.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" struct HostPortKey { HostPortKey() @@ -34,13 +36,14 @@ struct HostPortKey ip.clear(); port = 0; proto = IpProtocol::PROTO_NOT_SET; + padding = 0; } bool operator<(HostPortKey right) const { - if( sfip_lesser(&ip, &right.ip) ) + if( ip.less_than(right.ip) ) return true; - else if( sfip_lesser(&right.ip, &ip) ) + else if( right.ip.less_than(ip) ) return false; else { @@ -55,10 +58,12 @@ struct HostPortKey } } - sfip_t ip; + SfIp ip; uint16_t port; IpProtocol proto; + char padding; }; +#pragma GCC diagnostic pop THREAD_LOCAL std::map* host_port_cache = nullptr; @@ -74,11 +79,11 @@ void HostPortCache::terminate() host_port_cache = nullptr; } -HostPortVal* HostPortCache::find(const sfip_t* ip, uint16_t port, IpProtocol protocol) +HostPortVal* HostPortCache::find(const SfIp* ip, uint16_t port, IpProtocol protocol) { HostPortKey hk; - sfip_set_ip(&hk.ip, ip); + hk.ip.set(*ip); hk.port = port; hk.proto = protocol; @@ -90,14 +95,15 @@ HostPortVal* HostPortCache::find(const sfip_t* ip, uint16_t port, IpProtocol pro return nullptr; } -bool HostPortCache::add(const sfip_t* ip, uint16_t port, IpProtocol proto, unsigned type, AppId appId) +bool HostPortCache::add(const SfIp* ip, uint16_t port, IpProtocol proto, unsigned type, AppId appId) { HostPortKey hk; HostPortVal hv; - sfip_set_ip(&hk.ip, ip); + hk.ip.set(*ip); hk.port = port; hk.proto = proto; + hv.appId = appId; hv.type = type; diff --git a/src/network_inspectors/appid/host_port_app_cache.h b/src/network_inspectors/appid/host_port_app_cache.h index 40a3b61cf..f5a3d1c2b 100644 --- a/src/network_inspectors/appid/host_port_app_cache.h +++ b/src/network_inspectors/appid/host_port_app_cache.h @@ -22,8 +22,7 @@ #ifndef HOST_PORT_APP_CACHE_H #define HOST_PORT_APP_CACHE_H -#include "protocols/protocol_ids.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" #include "appid_api.h" struct HostPortVal @@ -37,8 +36,8 @@ class HostPortCache public: static void initialize(); static void terminate(); - static HostPortVal* find(const sfip_t*, uint16_t port, IpProtocol proto); - static bool add(const sfip_t*, uint16_t port, IpProtocol proto, unsigned type, AppId); + static HostPortVal* find(const SfIp*, uint16_t port, IpProtocol proto); + static bool add(const SfIp*, uint16_t port, IpProtocol proto, unsigned type, AppId); static void dump(); }; diff --git a/src/network_inspectors/appid/lua_detector_api.cc b/src/network_inspectors/appid/lua_detector_api.cc index 5aa8046ed..826222f2d 100644 --- a/src/network_inspectors/appid/lua_detector_api.cc +++ b/src/network_inspectors/appid/lua_detector_api.cc @@ -100,7 +100,7 @@ void free_chp_glossary() CHP_glossary = nullptr; } -static inline int convert_string_to_address(const char* string, sfip_t* address) +static inline int convert_string_to_address(const char* string, SfIp* address) { int af; struct in6_addr buf; @@ -114,7 +114,7 @@ static inline int convert_string_to_address(const char* string, sfip_t* address) if (inet_pton(af, string, &buf)) { - if (sfip_set_raw(address, &buf, af) != SFIP_SUCCESS) + if (address->set(&buf, af) != SFIP_SUCCESS) return 0; } else @@ -874,9 +874,9 @@ static int detector_get_packet_src_addr(lua_State* L) { auto& ud = *UserData::check(L, DETECTOR, 1); - const sfip_t* ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_src(); + const SfIp* ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_src(); lua_checkstack (L, 1); - lua_pushnumber(L, ipAddr->ip32[0]); + lua_pushnumber(L, ipAddr->get_ip4_value()); return 1; } @@ -891,9 +891,9 @@ static int detector_get_packet_dst_addr(lua_State* L) { auto& ud = *UserData::check(L, DETECTOR, 1); - const sfip_t* ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_dst(); + const SfIp* ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_dst(); lua_checkstack (L, 1); - lua_pushnumber(L, ipAddr->ip32[0]); + lua_pushnumber(L, ipAddr->get_ip4_value()); return 1; } @@ -1188,7 +1188,7 @@ static int detector_get_flow(lua_State* L) return 1; } -int detector_add_http_pattern(lua_State* L) +static int detector_add_http_pattern(lua_State* L) { int index = 1; @@ -1269,7 +1269,7 @@ int detector_add_http_pattern(lua_State* L) /* On the lua side, this should look something like: addSSLCertPattern(, '' ) */ -int detector_add_ssl_cert_pattern(lua_State* L) +static int detector_add_ssl_cert_pattern(lua_State* L) { int index = 1; @@ -1308,7 +1308,7 @@ int detector_add_ssl_cert_pattern(lua_State* L) } // for Lua this looks something like: addDNSHostPattern(, '') -int detector_add_dns_host_pattern(lua_State* L) +static int detector_add_dns_host_pattern(lua_State* L) { int index = 1; @@ -1382,7 +1382,7 @@ static int detector_add_ssl_cname_pattern(lua_State* L) static int detector_add_host_port_application(lua_State* L) { int index = 1; - sfip_t ip_addr; + SfIp ip_addr; auto& ud = *UserData::check(L, DETECTOR, index++); if ( ud->validateParams.pkt ) @@ -2606,8 +2606,8 @@ static int detector_add_sip_server(lua_State* L) */ static int create_future_flow(lua_State* L) { - sfip_t client_addr; - sfip_t server_addr; + SfIp client_addr; + SfIp server_addr; int16_t snort_app_id = 0; auto& ud = *UserData::check(L, DETECTOR, 1); diff --git a/src/network_inspectors/appid/lua_detector_flow_api.cc b/src/network_inspectors/appid/lua_detector_flow_api.cc index 26b940605..3ce5837f8 100644 --- a/src/network_inspectors/appid/lua_detector_flow_api.cc +++ b/src/network_inspectors/appid/lua_detector_flow_api.cc @@ -155,8 +155,8 @@ static inline uint64_t convert_flags_c_to_lua(uint64_t in) */ static int create_detector_flow(lua_State* L) { - sfip_t saddr; - sfip_t daddr; + SfIp saddr; + SfIp daddr; auto& detector_data = *UserData::check(L, DETECTOR, 1); @@ -169,12 +169,12 @@ static int create_detector_flow(lua_State* L) if (patternLen == 16) { - if (sfip_set_raw(&saddr, pattern, AF_INET6) != SFIP_SUCCESS) + if (saddr.set(pattern, AF_INET6) != SFIP_SUCCESS) return 0; } else if (patternLen == 4) { - if (sfip_set_raw(&saddr, pattern, AF_INET) != SFIP_SUCCESS) + if (saddr.set(pattern, AF_INET) != SFIP_SUCCESS) return 0; } else @@ -186,12 +186,12 @@ static int create_detector_flow(lua_State* L) if (patternLen == 16) { - if (sfip_set_raw(&daddr, pattern, AF_INET6) != SFIP_SUCCESS) + if (daddr.set(pattern, AF_INET6) != SFIP_SUCCESS) return 0; } else if (patternLen == 4) { - if (sfip_set_raw(&daddr, pattern, AF_INET) != SFIP_SUCCESS) + if (daddr.set(pattern, AF_INET) != SFIP_SUCCESS) return 0; } else diff --git a/src/network_inspectors/appid/service_plugins/service_base.cc b/src/network_inspectors/appid/service_plugins/service_base.cc index 964737446..5b382f667 100644 --- a/src/network_inspectors/appid/service_plugins/service_base.cc +++ b/src/network_inspectors/appid/service_plugins/service_base.cc @@ -1100,7 +1100,7 @@ static int AppIdServiceAddServiceEx(AppIdSession* asd, const Packet* pkt, int di { AppIdServiceIDState* id_state = nullptr; uint16_t port = 0; - const sfip_t* ip = nullptr; + const SfIp* ip = nullptr; if ( !pkt || !svc_element ) { @@ -1175,7 +1175,7 @@ static int AppIdServiceAddServiceEx(AppIdSession* asd, const Packet* pkt, int di id_state->current_service = nullptr; } - if (!sfip_is_set(&asd->service_ip)) + if (!asd->service_ip.is_set()) { asd->service_ip = *ip; asd->service_port = port; @@ -1289,7 +1289,7 @@ int AppIdServiceInProcess(AppIdSession* asd, const Packet* pkt, int dir, asd->get_session_flags(APPID_SESSION_IGNORE_HOST | APPID_SESSION_UDP_REVERSED)) return SERVICE_SUCCESS; - const sfip_t* ip = pkt->ptrs.ip_api.get_src(); + const SfIp* ip = pkt->ptrs.ip_api.get_src(); uint16_t port = asd->service_port ? asd->service_port : pkt->ptrs.sp; id_state = AppIdServiceState::get(ip, asd->protocol, port, get_service_detect_level(asd)); if ( !id_state ) @@ -1302,7 +1302,7 @@ int AppIdServiceInProcess(AppIdSession* asd, const Packet* pkt, int dir, } else { - if (!sfip_is_set(&asd->service_ip)) + if (!asd->service_ip.is_set()) { asd->service_ip = *(pkt->ptrs.ip_api.get_src()); if (!asd->service_port) @@ -1344,7 +1344,7 @@ int AppIdServiceIncompatibleData(AppIdSession* asd, const Packet* pkt, int dir, /* If we're still working on a port/pattern list of detectors, then ignore * individual fails until we're done looking at everything. */ - const sfip_t* ip = pkt->ptrs.ip_api.get_src(); + const SfIp* ip = pkt->ptrs.ip_api.get_src(); uint16_t port = asd->service_port ? asd->service_port : pkt->ptrs.sp; AppIdServiceIDState* id_state = AppIdServiceState::get(ip, asd->protocol, port, get_service_detect_level(asd)); if ( (asd->serviceData == nullptr) && (asd->candidate_service_list != nullptr) @@ -1386,7 +1386,7 @@ int AppIdServiceIncompatibleData(AppIdSession* asd, const Packet* pkt, int dir, } else { - if (!sfip_is_set(&asd->service_ip)) + if (!asd->service_ip.is_set()) { asd->service_ip = *(pkt->ptrs.ip_api.get_src()); if (!asd->service_port) @@ -1420,7 +1420,7 @@ int AppIdServiceIncompatibleData(AppIdSession* asd, const Packet* pkt, int dir, int AppIdServiceFailService(AppIdSession* asd, const Packet* pkt, int dir, const RNAServiceElement* svc_element, unsigned flow_data_index) { - const sfip_t* ip = pkt->ptrs.ip_api.get_src(); + const SfIp* ip = pkt->ptrs.ip_api.get_src(); uint16_t port = asd->service_port ? asd->service_port : pkt->ptrs.sp; AppIdServiceIDState* id_state = AppIdServiceState::get(ip, asd->protocol, port, get_service_detect_level(asd)); @@ -1470,7 +1470,7 @@ int AppIdServiceFailService(AppIdSession* asd, const Packet* pkt, int dir, } else { - if (!sfip_is_set(&asd->service_ip)) + if (!asd->service_ip.is_set()) { asd->service_ip = *(pkt->ptrs.ip_api.get_src()); if (!asd->service_port) @@ -1502,7 +1502,7 @@ int AppIdServiceFailService(AppIdSession* asd, const Packet* pkt, int dir, * simply because of unrecognized client data, then consider retrying * the search again. */ static void HandleFailure(AppIdSession* asd, AppIdServiceIDState* id_state, - const sfip_t* client_ip, unsigned timeout) + const SfIp* client_ip, unsigned timeout) { /* If we had a valid detector, check for too many fails. If so, start * search sequence again. */ @@ -1531,7 +1531,7 @@ static void HandleFailure(AppIdSession* asd, AppIdServiceIDState* id_state, * search process over. */ else if (id_state->invalid_client_count == 0) { - if (sfip_fast_eq6(&id_state->last_detract, client_ip)) + if (id_state->last_detract.fast_eq6(*client_ip)) id_state->detract_count++; else id_state->last_detract = *client_ip; @@ -1610,7 +1610,7 @@ void FailInProcessService(AppIdSession* asd, const AppIdConfig*) (id_state->svc && id_state->svc->name) ? id_state->svc->name : "UNKNOWN"); id_state->invalid_client_count += STATE_ID_INCONCLUSIVE_SERVICE_WEIGHT; - if (sfip_fast_eq6(&asd->flow->server_ip, &asd->service_ip)) + if (asd->flow->server_ip.fast_eq6(asd->service_ip)) HandleFailure(asd, id_state, &asd->flow->client_ip, 1); else HandleFailure(asd, id_state, &asd->flow->server_ip, 1); @@ -1680,7 +1680,7 @@ static const RNAServiceElement* get_next_service(const Packet* p, const int dir, SF_LNODE* iter; AppIdServiceIDState* reverse_id_state; const RNAServiceElement* reverse_service = nullptr; - const sfip_t* reverse_ip = p->ptrs.ip_api.get_src(); + const SfIp* reverse_ip = p->ptrs.ip_api.get_src(); asd->tried_reverse_service = true; if ((reverse_id_state = AppIdServiceState::get(reverse_ip, proto, p->ptrs.sp, get_service_detect_level(asd)))) @@ -1728,7 +1728,7 @@ static const RNAServiceElement* get_next_service(const Packet* p, const int dir, int AppIdDiscoverService(Packet* p, const int dir, AppIdSession* asd) { - const sfip_t* ip = nullptr; + const SfIp* ip = nullptr; int ret = SERVICE_NOMATCH; const RNAServiceElement* service = nullptr; uint16_t port = 0; @@ -1736,7 +1736,7 @@ int AppIdDiscoverService(Packet* p, const int dir, AppIdSession* asd) /* Get packet info. */ auto proto = asd->protocol; - if (sfip_is_set(&asd->service_ip)) + if (asd->service_ip.is_set()) { ip = &asd->service_ip; port = asd->service_port; @@ -1908,7 +1908,7 @@ int AppIdDiscoverService(Packet* p, const int dir, AppIdSession* asd) /* Handle failure exception cases in states. */ if ((ret != SERVICE_INPROCESS) && (ret != SERVICE_SUCCESS)) { - const sfip_t* tmp_ip; + const SfIp* tmp_ip; if (dir == APP_ID_FROM_RESPONDER) tmp_ip = p->ptrs.ip_api.get_dst(); else @@ -1918,7 +1918,7 @@ int AppIdDiscoverService(Packet* p, const int dir, AppIdSession* asd) { if (id_state->invalid_client_count < STATE_ID_INVALID_CLIENT_THRESHOLD) { - if (sfip_fast_equals_raw(&id_state->last_invalid_client, tmp_ip)) + if (id_state->last_invalid_client.fast_equals_raw(*tmp_ip)) id_state->invalid_client_count++; else { diff --git a/src/network_inspectors/appid/service_plugins/service_ftp.cc b/src/network_inspectors/appid/service_plugins/service_ftp.cc index d4e5d5901..fb9a566c7 100644 --- a/src/network_inspectors/appid/service_plugins/service_ftp.cc +++ b/src/network_inspectors/appid/service_plugins/service_ftp.cc @@ -68,7 +68,7 @@ struct ServiceFTPData char vendor[MAX_STRING_SIZE]; char version[MAX_STRING_SIZE]; FTPCmd cmd; - sfip_t address; + SfIp address; uint16_t port; }; @@ -704,7 +704,7 @@ static int ftp_validate_epsv(const uint8_t* data, uint16_t size, } static int ftp_validate_port(const uint8_t* data, uint16_t size, - sfip_t* address, uint16_t* port) + SfIp* address, uint16_t* port) { const uint8_t* end; const uint8_t* p; @@ -712,7 +712,7 @@ static int ftp_validate_port(const uint8_t* data, uint16_t size, uint32_t addr; uint32_t addr2; - memset(address,0,sizeof(sfip_t)); + memset(address,0,sizeof(*address)); *port = 0; end = data + size; @@ -729,8 +729,8 @@ static int ftp_validate_port(const uint8_t* data, uint16_t size, if (ftp_decode_octet(&data, end, ',', &tmp)) return -1; addr += tmp; - addr2 = htonl(addr); // make it network order before calling sfip_set_raw() - sfip_set_raw(address, &addr2, AF_INET); + addr2 = htonl(addr); // make it network order before calling sfip set() + address->set(&addr2, AF_INET); if (ftp_decode_octet(&data, end, ',', &tmp)) return -1; @@ -770,7 +770,7 @@ static addr_family_map RFC2428_known_address_families[] = { 0, 0 } }; -static int ftp_validate_eprt(const uint8_t* data, uint16_t size, sfip_t* address, uint16_t* port) +static int ftp_validate_eprt(const uint8_t* data, uint16_t size, SfIp* address, uint16_t* port) { int index; int addrFamilySupported = 0; @@ -779,7 +779,7 @@ static int ftp_validate_eprt(const uint8_t* data, uint16_t size, sfip_t* address uint32_t tmp; char tmp_str[INET6_ADDRSTRLEN+1]; - memset(address, 0, sizeof(sfip_t)); + memset(address, 0, sizeof(*address)); *port = 0; end = data + size; @@ -809,11 +809,9 @@ static int ftp_validate_eprt(const uint8_t* data, uint16_t size, sfip_t* address tmp_str[index] = '\0'; // make the copied portion be nul terminated. // FIXIT-L recode logic above and this call to call sfip_pton instead... - if (sfip_convert_ip_text_to_binary(addrFamilySupported, tmp_str, &address) != SFIP_SUCCESS) + if (address->pton(addrFamilySupported, tmp_str) != SFIP_SUCCESS) return -1; - address->family = addrFamilySupported; - data++; // skip the delimiter at the end of the address substring. if (ftp_decode_port_number(&data, end, delimiter, &tmp)) // an error is returned if port was // greater than 65535 @@ -1176,21 +1174,21 @@ static int ftp_validate(ServiceValidationArgs* args) &address, &port); if (!code) { - sfip_t ip; - const sfip_t* sip; - const sfip_t* dip; + SfIp ip; + const SfIp* sip; + const SfIp* dip; uint32_t addr; dip = pkt->ptrs.ip_api.get_dst(); sip = pkt->ptrs.ip_api.get_src(); addr = htonl(address); - sfip_set_raw(&ip, &addr, AF_INET); + ip.set(&addr, AF_INET); fp = AppIdSession::create_future_session(pkt, dip, 0, &ip, port, asd->protocol, ftp_data_app_id, APPID_EARLY_SESSION_FLAG_FW_RULE); if (fp) InitializeDataSession(asd,fp); - if (!sfip_fast_eq6(&ip, sip)) + if (!ip.fast_eq6(*sip)) { fp = asd->create_future_session(pkt, dip, 0, sip, port, asd->protocol, ftp_data_app_id, APPID_EARLY_SESSION_FLAG_FW_RULE); @@ -1210,8 +1208,8 @@ static int ftp_validate(ServiceValidationArgs* args) if (!code) { - const sfip_t* sip; - const sfip_t* dip; + const SfIp* sip; + const SfIp* dip; dip = pkt->ptrs.ip_api.get_dst(); sip = pkt->ptrs.ip_api.get_src(); fp = asd->create_future_session(pkt, dip, 0, sip, port, asd->protocol, @@ -1228,7 +1226,7 @@ static int ftp_validate(ServiceValidationArgs* args) case 200: if (fd->cmd == FTP_CMD_PORT_EPRT) { - const sfip_t* sip; + const SfIp* sip; sip = pkt->ptrs.ip_api.get_src(); fp = asd->create_future_session(pkt, sip, 0, &fd->address, fd->port, asd->protocol, ftp_data_app_id, APPID_EARLY_SESSION_FLAG_FW_RULE); diff --git a/src/network_inspectors/appid/service_plugins/service_rexec.cc b/src/network_inspectors/appid/service_plugins/service_rexec.cc index 01f582658..ad1bd868d 100644 --- a/src/network_inspectors/appid/service_plugins/service_rexec.cc +++ b/src/network_inspectors/appid/service_plugins/service_rexec.cc @@ -185,8 +185,8 @@ static int rexec_validate(ServiceValidationArgs* args) goto bail; if (port && pkt) { - const sfip_t* sip; - const sfip_t* dip; + const SfIp* sip; + const SfIp* dip; dip = pkt->ptrs.ip_api.get_dst(); sip = pkt->ptrs.ip_api.get_src(); diff --git a/src/network_inspectors/appid/service_plugins/service_rpc.cc b/src/network_inspectors/appid/service_plugins/service_rpc.cc index e25b37d1f..76483a44b 100644 --- a/src/network_inspectors/appid/service_plugins/service_rpc.cc +++ b/src/network_inspectors/appid/service_plugins/service_rpc.cc @@ -439,8 +439,8 @@ static int validate_packet(const uint8_t* data, uint16_t size, int dir, AppIdSes pmr = (ServiceRPCPortmapReply*)data; if (pmr->port) { - const sfip_t* dip = pkt->ptrs.ip_api.get_dst(); - const sfip_t* sip = pkt->ptrs.ip_api.get_src(); + const SfIp* dip = pkt->ptrs.ip_api.get_dst(); + const SfIp* sip = pkt->ptrs.ip_api.get_src(); tmp = ntohl(pmr->port); pf = AppIdSession::create_future_session(pkt, dip, 0, sip, (uint16_t)tmp, (IpProtocol)ntohl((uint32_t)rd->proto), app_id, 0); diff --git a/src/network_inspectors/appid/service_plugins/service_rshell.cc b/src/network_inspectors/appid/service_plugins/service_rshell.cc index d581da594..f4db2b6cd 100644 --- a/src/network_inspectors/appid/service_plugins/service_rshell.cc +++ b/src/network_inspectors/appid/service_plugins/service_rshell.cc @@ -183,8 +183,8 @@ static int rshell_validate(ServiceValidationArgs* args) tmp_rd = (ServiceRSHELLData*)snort_calloc(sizeof(ServiceRSHELLData)); tmp_rd->state = RSHELL_STATE_STDERR_CONNECT_SYN; tmp_rd->parent = rd; - const sfip_t* dip = pkt->ptrs.ip_api.get_dst(); - const sfip_t* sip = pkt->ptrs.ip_api.get_src(); + const SfIp* dip = pkt->ptrs.ip_api.get_dst(); + const SfIp* sip = pkt->ptrs.ip_api.get_src(); pf = AppIdSession::create_future_session(pkt, dip, 0, sip, (uint16_t)port, IpProtocol::TCP, app_id, APPID_EARLY_SESSION_FLAG_FW_RULE); if (pf) diff --git a/src/network_inspectors/appid/service_plugins/service_snmp.cc b/src/network_inspectors/appid/service_plugins/service_snmp.cc index a8f396c3c..06490bce7 100644 --- a/src/network_inspectors/appid/service_plugins/service_snmp.cc +++ b/src/network_inspectors/appid/service_plugins/service_snmp.cc @@ -516,8 +516,8 @@ static int snmp_validate(ServiceValidationArgs* args) sd->state = SNMP_STATE_RESPONSE; /*adding expected connection in case the server doesn't send from 161*/ - const sfip_t* dip = pkt->ptrs.ip_api.get_dst(); - const sfip_t* sip = pkt->ptrs.ip_api.get_src(); + const SfIp* dip = pkt->ptrs.ip_api.get_dst(); + const SfIp* sip = pkt->ptrs.ip_api.get_src(); pf = AppIdSession::create_future_session(pkt, dip, 0, sip, pkt->ptrs.sp, asd->protocol, app_id, 0); if (pf) { diff --git a/src/network_inspectors/appid/service_plugins/service_ssl.cc b/src/network_inspectors/appid/service_plugins/service_ssl.cc index eec2edc85..acb7bcd4e 100644 --- a/src/network_inspectors/appid/service_plugins/service_ssl.cc +++ b/src/network_inspectors/appid/service_plugins/service_ssl.cc @@ -1150,8 +1150,8 @@ bool setSSLSquelch(Packet* p, int type, AppId appId) if (!AppInfoManager::get_instance().get_app_info_flags(appId, APPINFO_FLAG_SSL_SQUELCH)) return false; - const sfip_t* dip = p->ptrs.ip_api.get_dst(); - const sfip_t* sip = p->ptrs.ip_api.get_src(); + const SfIp* dip = p->ptrs.ip_api.get_dst(); + const SfIp* sip = p->ptrs.ip_api.get_src(); if (!(f = AppIdSession::create_future_session(p, sip, 0, dip, p->ptrs.dp, IpProtocol::TCP, appId, 0))) diff --git a/src/network_inspectors/appid/service_plugins/service_tftp.cc b/src/network_inspectors/appid/service_plugins/service_tftp.cc index 1d4e4bc45..20578b24f 100644 --- a/src/network_inspectors/appid/service_plugins/service_tftp.cc +++ b/src/network_inspectors/appid/service_plugins/service_tftp.cc @@ -169,8 +169,8 @@ static int tftp_validate(ServiceValidationArgs* args) uint16_t block = 0; uint16_t tmp = 0; AppIdSession* pf = nullptr; - const sfip_t* sip = nullptr; - const sfip_t* dip = nullptr; + const SfIp* sip = nullptr; + const SfIp* dip = nullptr; AppIdSession* asd = args->asd; const uint8_t* data = args->data; Packet* pkt = args->pkt; diff --git a/src/network_inspectors/appid/service_state.cc b/src/network_inspectors/appid/service_state.cc index a19246aba..e3879cee9 100644 --- a/src/network_inspectors/appid/service_state.cc +++ b/src/network_inspectors/appid/service_state.cc @@ -30,6 +30,8 @@ //#define DEBUG_SERVICE_STATE 1 +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" class AppIdServiceStateKey { public: @@ -37,15 +39,16 @@ public: { ip.clear(); port = 0; - proto = IpProtocol::PROTO_NOT_SET; level = 0; + proto = IpProtocol::PROTO_NOT_SET; + padding[0] = padding[1] = padding[2] = 0; } bool operator<(AppIdServiceStateKey right) const { - if( sfip_lesser(&ip, &right.ip) ) + if( ip.less_than(right.ip) ) return true; - else if( sfip_lesser(&right.ip, &ip) ) + else if( right.ip.less_than(ip) ) return false; else { @@ -64,11 +67,13 @@ public: } } - sfip_t ip; + SfIp ip; uint16_t port; - IpProtocol proto; uint32_t level; + IpProtocol proto; + char padding[3]; }; +#pragma GCC diagnostic pop // FIXIT-L - no memcap on size of this table, do we need that? THREAD_LOCAL std::map* service_state_cache = nullptr; @@ -88,13 +93,13 @@ void AppIdServiceState::clean(void) service_state_cache = nullptr; } -AppIdServiceIDState* AppIdServiceState::add(const sfip_t* ip, IpProtocol proto, uint16_t port, +AppIdServiceIDState* AppIdServiceState::add(const SfIp* ip, IpProtocol proto, uint16_t port, uint32_t level) { AppIdServiceStateKey ssk; AppIdServiceIDState* ss = nullptr; - sfip_set_ip(&ssk.ip, ip); + ssk.ip.set(*ip); ssk.proto = proto; ssk.port = port; ssk.level = level; @@ -123,7 +128,7 @@ AppIdServiceIDState* AppIdServiceState::add(const sfip_t* ip, IpProtocol proto, return ss; } -AppIdServiceIDState* AppIdServiceState::get(const sfip_t* ip, IpProtocol proto, uint16_t port, +AppIdServiceIDState* AppIdServiceState::get(const SfIp* ip, IpProtocol proto, uint16_t port, uint32_t level) { AppIdServiceStateKey ssk; @@ -131,7 +136,7 @@ AppIdServiceIDState* AppIdServiceState::get(const sfip_t* ip, IpProtocol proto, char ipstr[INET6_ADDRSTRLEN]; // FIXIT-M ASAN reports mem leak on ServiceMatch* objects if this is not defined // which makes no sense, need to investigate further - sfip_set_ip(&ssk.ip, ip); + ssk.ip.set(*ip); ssk.proto = proto; ssk.port = port; ssk.level = level; @@ -160,11 +165,11 @@ AppIdServiceIDState* AppIdServiceState::get(const sfip_t* ip, IpProtocol proto, return ss; } -void AppIdServiceState::remove(const sfip_t* ip, IpProtocol proto, uint16_t port, uint32_t level) +void AppIdServiceState::remove(const SfIp* ip, IpProtocol proto, uint16_t port, uint32_t level) { AppIdServiceStateKey ssk; - sfip_set_ip(&ssk.ip, ip); + ssk.ip.set(*ip); ssk.proto = proto; ssk.port = port; ssk.level = level; diff --git a/src/network_inspectors/appid/service_state.h b/src/network_inspectors/appid/service_state.h index f00c7d4c9..d1c26f744 100644 --- a/src/network_inspectors/appid/service_state.h +++ b/src/network_inspectors/appid/service_state.h @@ -22,8 +22,7 @@ #ifndef SERVICE_STATE_H #define SERVICE_STATE_H -#include "sfip/sfip_t.h" -#include "protocols/protocol_ids.h" +#include "sfip/sf_ip.h" #include "utils/util.h" struct RNAServiceElement; @@ -95,7 +94,7 @@ struct AppIdServiceIDState SERVICE_ID_STATE state = SERVICE_ID_NEW; unsigned valid_count = 0; unsigned detract_count = 0; - sfip_t last_detract; + SfIp last_detract; /**Number of consequetive flows that were declared incompatible by detectors. Incompatibility * means client packet did not match. @@ -106,7 +105,7 @@ struct AppIdServiceIDState * different everytime, then consequetive incompatible status indicate that flow is not using * specific service. */ - sfip_t last_invalid_client; + SfIp last_invalid_client; /** Count for number of unknown sessions saved */ @@ -131,9 +130,9 @@ class AppIdServiceState public: static void initialize(unsigned long); static void clean(); - static AppIdServiceIDState* add( const sfip_t*, IpProtocol proto, uint16_t port, uint32_t level); - static AppIdServiceIDState* get( const sfip_t*, IpProtocol proto, uint16_t port, uint32_t level); - static void remove(const sfip_t*, IpProtocol proto, uint16_t port, uint32_t level); + static AppIdServiceIDState* add( const SfIp*, IpProtocol proto, uint16_t port, uint32_t level); + static AppIdServiceIDState* get( const SfIp*, IpProtocol proto, uint16_t port, uint32_t level); + static void remove(const SfIp*, IpProtocol proto, uint16_t port, uint32_t level); static void dump_stats(); }; diff --git a/src/network_inspectors/appid/test/appid_http_event_test.cc b/src/network_inspectors/appid/test/appid_http_event_test.cc index 6b45869c8..14f60a161 100644 --- a/src/network_inspectors/appid/test/appid_http_event_test.cc +++ b/src/network_inspectors/appid/test/appid_http_event_test.cc @@ -84,7 +84,7 @@ unsigned AppIdSession::flow_id = 0; AppIdSession *fake_session = nullptr; FakeHttpMsgHeader *fake_msg_header = nullptr; -AppIdSession::AppIdSession(IpProtocol, const sfip_t*, uint16_t) : FlowData(flow_id, nullptr) +AppIdSession::AppIdSession(IpProtocol, const SfIp*, uint16_t) : FlowData(flow_id, nullptr) { hsession = nullptr; } diff --git a/src/network_inspectors/arp_spoof/arp_spoof.cc b/src/network_inspectors/arp_spoof/arp_spoof.cc index eabee8863..0e75ed757 100644 --- a/src/network_inspectors/arp_spoof/arp_spoof.cc +++ b/src/network_inspectors/arp_spoof/arp_spoof.cc @@ -124,9 +124,9 @@ static void PrintIPMacEntryList(IPMacEntryList& ipmel) for ( auto p : ipmel ) { - sfip_t in; - sfip_set_raw(&in, &p.ipv4_addr, AF_INET); - LogMessage(" %s -> ", inet_ntoa(&in)); + SfIp in; + in.set(&p.ipv4_addr, AF_INET); + LogMessage(" %s -> ", in.ntoa()); for (int i = 0; i < 6; i++) { diff --git a/src/network_inspectors/binder/test/binder_test.cc b/src/network_inspectors/binder/test/binder_test.cc index 79849f68a..18770f548 100644 --- a/src/network_inspectors/binder/test/binder_test.cc +++ b/src/network_inspectors/binder/test/binder_test.cc @@ -42,7 +42,7 @@ static const PegInfo bind_pegs[] = { { nullptr, nullptr } }; static std::vector s_bindings; -static sfip_t s_src_ip, s_dst_ip; +static SfIp s_src_ip, s_dst_ip; static Inspector* s_inspector; void show_stats(PegCount*, const PegInfo*, unsigned, const char*) { } @@ -50,7 +50,7 @@ void show_stats(PegCount*, const PegInfo*, IndexVec&, const char*) { } void show_stats(PegCount*, const PegInfo*, IndexVec&, const char*, FILE*) { } void sfvar_free(sfip_var_t*) {} -bool sfvar_ip_in(sfip_var_t*, const sfip_t*) { return false; } +bool sfvar_ip_in(sfip_var_t*, const SfIp*) { return false; } SO_PUBLIC Inspector* InspectorManager::get_inspector(const char*, bool) { return s_inspector; } InspectorType InspectorManager::get_type(const char*) { return InspectorType::IT_BINDER; } Inspector* InspectorManager::get_binder() { return nullptr; } @@ -97,7 +97,7 @@ void Stream::set_splitter(Flow*, bool, class StreamSplitter*) { } const char* get_protocol_name(uint16_t) { return ""; } int16_t FindProtocolReference(const char*) { return 0; } void set_policies(SnortConfig*, unsigned) { } -HostAttributeEntry* SFAT_LookupHostEntryByIP(const sfip_t*) { return nullptr; } +HostAttributeEntry* SFAT_LookupHostEntryByIP(const SfIp*) { return nullptr; } Flow::Flow() { } Flow::~Flow() { } diff --git a/src/network_inspectors/packet_capture/packet_capture.cc b/src/network_inspectors/packet_capture/packet_capture.cc index 0eadb954f..fe7e1b8ca 100644 --- a/src/network_inspectors/packet_capture/packet_capture.cc +++ b/src/network_inspectors/packet_capture/packet_capture.cc @@ -32,6 +32,7 @@ #include "log/messages.h" #include "main/snort_config.h" #include "main/thread.h" +#include "protocols/packet.h" #include "utils/util.h" #ifdef UNIT_TEST diff --git a/src/network_inspectors/perf_monitor/flow_ip_tracker.cc b/src/network_inspectors/perf_monitor/flow_ip_tracker.cc index 91e6e9410..6a47b2032 100644 --- a/src/network_inspectors/perf_monitor/flow_ip_tracker.cc +++ b/src/network_inspectors/perf_monitor/flow_ip_tracker.cc @@ -19,39 +19,41 @@ // flow_ip_tracker.cc author Carter Waxman #include "flow_ip_tracker.h" -#include "perf_module.h" #include "log/messages.h" #include "sfip/sf_ip.h" #include "utils/util.h" +#include "utils/util_net.h" + +#include "perf_module.h" #define FLIP_FILE (PERF_NAME "_flow_ip.csv") struct FlowStateKey { - sfip_t ipA; - sfip_t ipB; + SfIp ipA; + SfIp ipB; }; THREAD_LOCAL FlowIPTracker* perf_flow_ip; -FlowStateValue* FlowIPTracker::find_stats(const sfip_t* src_addr, const sfip_t* dst_addr, +FlowStateValue* FlowIPTracker::find_stats(const SfIp* src_addr, const SfIp* dst_addr, int* swapped) { SFXHASH_NODE* node; FlowStateKey key; FlowStateValue* value; - if (sfip_lesser(src_addr, dst_addr)) + if (src_addr->less_than(*dst_addr)) { - sfip_copy(key.ipA, src_addr); - sfip_copy(key.ipB, dst_addr); + key.ipA.set(*src_addr); + key.ipB.set(*dst_addr); *swapped = 0; } else { - sfip_copy(key.ipA, dst_addr); - sfip_copy(key.ipB, src_addr); + key.ipA.set(*dst_addr); + key.ipB.set(*src_addr); *swapped = 1; } @@ -147,8 +149,8 @@ void FlowIPTracker::update(Packet* p) FlowType type = SFS_TYPE_OTHER; int swapped; - const sfip_t* src_addr = p->ptrs.ip_api.get_src(); - const sfip_t* dst_addr = p->ptrs.ip_api.get_dst(); + const SfIp* src_addr = p->ptrs.ip_api.get_src(); + const SfIp* dst_addr = p->ptrs.ip_api.get_dst(); int len = p->pkth->caplen; if (p->ptrs.tcph) @@ -184,8 +186,8 @@ void FlowIPTracker::process(bool) FlowStateKey* key = (FlowStateKey*)node->key; FlowStateValue* cur_stats = (FlowStateValue*)node->data; - sfip_raw_ntop(key->ipA.family, key->ipA.ip32, ip_a, sizeof(ip_a)); - sfip_raw_ntop(key->ipB.family, key->ipB.ip32, ip_b, sizeof(ip_b)); + key->ipA.ntop(ip_a, sizeof(ip_a)); + key->ipB.ntop(ip_b, sizeof(ip_b)); memcpy(&stats, cur_stats, sizeof(stats)); write(); @@ -195,7 +197,7 @@ void FlowIPTracker::process(bool) reset(); } -int FlowIPTracker::update_state(const sfip_t* src_addr, const sfip_t* dst_addr, FlowState state) +int FlowIPTracker::update_state(const SfIp* src_addr, const SfIp* dst_addr, FlowState state) { int swapped; diff --git a/src/network_inspectors/perf_monitor/flow_ip_tracker.h b/src/network_inspectors/perf_monitor/flow_ip_tracker.h index e7b0f4202..f1cbc43fc 100644 --- a/src/network_inspectors/perf_monitor/flow_ip_tracker.h +++ b/src/network_inspectors/perf_monitor/flow_ip_tracker.h @@ -66,14 +66,14 @@ public: void update(Packet*) override; void process(bool) override; - int update_state(const sfip_t* src_addr, const sfip_t* dst_addr, FlowState); + int update_state(const SfIp* src_addr, const SfIp* dst_addr, FlowState); private: FlowStateValue stats; SFXHASH* ipMap; char ip_a[41], ip_b[41]; - FlowStateValue* find_stats(const sfip_t* src_addr, const sfip_t* dst_addr, int* swapped); + FlowStateValue* find_stats(const SfIp* src_addr, const SfIp* dst_addr, int* swapped); void write_stats(); void display_stats(); }; diff --git a/src/network_inspectors/port_scan/ipobj.cc b/src/network_inspectors/port_scan/ipobj.cc index 0d0ad15d5..4cc40fa2b 100644 --- a/src/network_inspectors/port_scan/ipobj.cc +++ b/src/network_inspectors/port_scan/ipobj.cc @@ -98,7 +98,7 @@ void ipset_free(IPSET* ipc) } } -int ipset_add(IPSET* ipset, sfip_t* ip, void* vport, int notflag) +int ipset_add(IPSET* ipset, SfCidr* ip, void* vport, int notflag) { if ( !ipset ) return -1; @@ -107,7 +107,7 @@ int ipset_add(IPSET* ipset, sfip_t* ip, void* vport, int notflag) PORTSET* portset = (PORTSET*)vport; IP_PORT* p = (IP_PORT*)snort_calloc(sizeof(IP_PORT)); - sfip_set_ip(&p->ip, ip); + p->ip.set(*ip); p->portset = *portset; p->notflag = (char)notflag; @@ -120,7 +120,7 @@ int ipset_add(IPSET* ipset, sfip_t* ip, void* vport, int notflag) return 0; } -int ipset_contains(IPSET* ipc, const sfip_t* ip, void* port) +int ipset_contains(IPSET* ipc, const SfIp* ip, void* port) { PORTRANGE* pr; unsigned short portu; @@ -140,7 +140,7 @@ int ipset_contains(IPSET* ipc, const sfip_t* ip, void* port) p!=0; p =(IP_PORT*)sflist_next(&cur_ip) ) { - if ( sfip_contains(&p->ip, ip) == SFIP_CONTAINS) + if (p->ip.contains(ip) == SFIP_CONTAINS) { SF_LNODE* cur_port; @@ -182,7 +182,7 @@ int ipset_print(IPSET* ipc) p!=0; p =(IP_PORT*)sflist_next(&cur_ip) ) { - SnortSnprintf(ip_str, 80, "%s", sfip_to_str(&p->ip)); + SnortSnprintf(ip_str, 80, "%s", p->ip.get_addr()->ntoa()); printf("CIDR BLOCK: %c%s", p->notflag ? '!' : ' ', ip_str); SF_LNODE* cur_port; @@ -294,7 +294,7 @@ static int port_parse(char* portstr, PORTSET* portset) return 0; } -static int ip_parse(char* ipstr, sfip_t* ip, char* not_flag, PORTSET* portset, char** endIP) +static int ip_parse(char* ipstr, SfCidr* ip, char* not_flag, PORTSET* portset, char** endIP) { char* port_str; char* comma; @@ -322,7 +322,7 @@ static int ip_parse(char* ipstr, sfip_t* ip, char* not_flag, PORTSET* portset, c *end_bracket = '\0'; } - if (sfip_pton(ipstr, ip) != SFIP_SUCCESS) + if (ip->set(ipstr) != SFIP_SUCCESS) return -1; /* Just to get the IP string out of the way */ @@ -385,7 +385,7 @@ int ipset_parse(IPSET* ipset, const char* ipstr) char set_not_flag = 0; char item_not_flag; char open_bracket = 0; - sfip_t ip; + SfCidr ip; PORTSET portset; copy = snort_strdup(ipstr); diff --git a/src/network_inspectors/port_scan/ipobj.h b/src/network_inspectors/port_scan/ipobj.h index 3f79ad951..2e4d94356 100644 --- a/src/network_inspectors/port_scan/ipobj.h +++ b/src/network_inspectors/port_scan/ipobj.h @@ -35,7 +35,7 @@ #include #include "utils/sflsq.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_cidr.h" struct PORTRANGE { @@ -50,7 +50,7 @@ struct PORTSET struct IP_PORT { - sfip_t ip; + SfCidr ip; PORTSET portset; char notflag; }; @@ -81,8 +81,8 @@ struct IPSET 255.255.255.255, or 0xffffffff, or -1. */ IPSET* ipset_new(); -int ipset_add(IPSET* ipset, sfip_t* ip, void* port, int notflag); -int ipset_contains(IPSET* ipset, const sfip_t* ip, void* port); +int ipset_add(IPSET* ipset, SfCidr* ip, void* port, int notflag); +int ipset_contains(IPSET* ipset, const SfIp* ip, void* port); IPSET* ipset_copy(IPSET* ipset); void ipset_free(IPSET* ipset); int ipset_print(IPSET* ipset); diff --git a/src/network_inspectors/port_scan/port_scan.cc b/src/network_inspectors/port_scan/port_scan.cc index 862f5c7cc..3736307ef 100644 --- a/src/network_inspectors/port_scan/port_scan.cc +++ b/src/network_inspectors/port_scan/port_scan.cc @@ -98,7 +98,7 @@ THREAD_LOCAL ProfileStats psPerfStats; static int MakeProtoInfo(PS_PROTO* proto, const u_char* buffer, u_int* total_size) { int dsize; - sfip_t* ip1, * ip2; + SfIp* ip1, * ip2; if (!total_size || !buffer) return -1; @@ -122,18 +122,18 @@ static int MakeProtoInfo(PS_PROTO* proto, const u_char* buffer, u_int* total_siz proto->priority_count, proto->connection_count, proto->u_ip_count, - inet_ntoa(ip1)); + ip1->ntoa()); /* Now print the high ip into the buffer. This saves us - * from having to copy the results of inet_ntoa (which is + * from having to copy the results of SfIp::ntoa (which is * a static buffer) to avoid the reuse of that buffer when - * more than one use of inet_ntoa is within the same printf. + * more than one use of SfIp::ntoa is within the same printf. */ SnortSnprintfAppend((char*)buffer, PROTO_BUFFER_SIZE, "%s\n" "Port/Proto Count: %d\n" "Port/Proto Range: %d:%d\n", - inet_ntoa(ip2), + ip2->ntoa(), proto->u_port_count, proto->low_p, proto->high_p); @@ -148,19 +148,19 @@ static int MakeProtoInfo(PS_PROTO* proto, const u_char* buffer, u_int* total_siz proto->priority_count, proto->connection_count, proto->u_ip_count, - inet_ntoa(ip1) + ip1->ntoa() ); /* Now print the high ip into the buffer. This saves us - * from having to copy the results of inet_ntoa (which is + * from having to copy the results of SfIp::ntoa (which is * a static buffer) to avoid the reuse of that buffer when - * more than one use of inet_ntoa is within the same printf. + * more than one use of SfIp::ntoa is within the same printf. */ SnortSnprintfAppend((char*)buffer, PROTO_BUFFER_SIZE, "%s\n" "Port/Proto Count: %d\n" "Port/Proto Range: %d:%d\n", - inet_ntoa(ip2), + ip2->ntoa(), proto->u_port_count, proto->low_p, proto->high_p); @@ -181,8 +181,8 @@ static int LogPortscanAlert(Packet* p, uint32_t event_id, uint32_t event_ref, uint32_t gen_id, uint32_t sig_id) { char timebuf[TIMEBUF_SIZE]; - const sfip_t* src_addr; - const sfip_t* dst_addr; + const SfIp* src_addr; + const SfIp* dst_addr; if(!p->ptrs.ip_api.is_ip()) return -1; @@ -205,8 +205,8 @@ static int LogPortscanAlert(Packet* p, uint32_t event_id, else fprintf(g_logfile, "event_ref: %u\n", event_ref); - fprintf(g_logfile, "%s ", inet_ntoa(p->ptrs.ip_api.get_src())); - fprintf(g_logfile, "-> %s\n", inet_ntoa(p->ptrs.ip_api.get_dst())); + fprintf(g_logfile, "%s ", p->ptrs.ip_api.get_src()->ntoa()); + fprintf(g_logfile, "-> %s\n", p->ptrs.ip_api.get_dst()->ntoa()); fprintf(g_logfile, "%.*s\n", p->dsize, p->data); fflush(g_logfile); @@ -670,16 +670,16 @@ static void PrintIPPortSet(IP_PORT* p) char ip_str[80], output_str[80]; PORTRANGE* pr; - SnortSnprintf(ip_str, sizeof(ip_str), "%s", sfip_to_str(&p->ip)); + SnortSnprintf(ip_str, sizeof(ip_str), "%s", p->ip.get_addr()->ntoa()); if (p->notflag) SnortSnprintf(output_str, sizeof(output_str), " !%s", ip_str); else SnortSnprintf(output_str, sizeof(output_str), " %s", ip_str); - if (((p->ip.family == AF_INET6) && (p->ip.bits != 128)) || - ((p->ip.family == AF_INET ) && (p->ip.bits != 32 ))) - SnortSnprintfAppend(output_str, sizeof(output_str), "/%d", p->ip.bits); + if (((p->ip.get_family() == AF_INET6) && (p->ip.get_bits() != 128)) || + ((p->ip.get_family() == AF_INET ) && (p->ip.get_bits() != 32 ))) + SnortSnprintfAppend(output_str, sizeof(output_str), "/%d", p->ip.get_bits()); SF_LNODE* cursor; pr=(PORTRANGE*)sflist_first(&p->portset.port_list, &cursor); diff --git a/src/network_inspectors/port_scan/ps_detect.cc b/src/network_inspectors/port_scan/ps_detect.cc index 367ea9cbb..a53a36bec 100644 --- a/src/network_inspectors/port_scan/ps_detect.cc +++ b/src/network_inspectors/port_scan/ps_detect.cc @@ -56,12 +56,15 @@ #include "sfip/sf_ip.h" #include "stream/stream.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpadded" typedef struct s_PS_HASH_KEY { int protocol; - sfip_t scanner; - sfip_t scanned; + SfIp scanner; + SfIp scanned; } PS_HASH_KEY; +#pragma GCC diagnostic pop typedef struct s_PS_ALERT_CONF { @@ -238,8 +241,8 @@ void ps_reset() /** ** Check scanner and scanned ips to see if we can filter them out. */ -int PortScan::ps_ignore_ip(const sfip_t* scanner, uint16_t scanner_port, - const sfip_t* scanned, uint16_t scanned_port) +int PortScan::ps_ignore_ip(const SfIp* scanner, uint16_t scanner_port, + const SfIp* scanned, uint16_t scanned_port) { if (config->ignore_scanners) { @@ -268,7 +271,7 @@ int PortScan::ps_filter_ignore(PS_PKT* ps_pkt) { Packet* p; int reverse_pkt = 0; - const sfip_t* scanner, * scanned; + const SfIp* scanner, * scanned; p = (Packet*)ps_pkt->pkt; @@ -447,12 +450,12 @@ int PortScan::ps_tracker_lookup(PS_PKT* ps_pkt, PS_TRACKER** scanner, if (config->detect_scan_type & (PS_TYPE_PORTSCAN | PS_TYPE_DECOYSCAN | PS_TYPE_DISTPORTSCAN)) { - sfip_clear(key.scanner); + key.scanner.clear(); if (ps_pkt->reverse_pkt) - sfip_copy(key.scanned, p->ptrs.ip_api.get_src()); + key.scanned.set(*p->ptrs.ip_api.get_src()); else - sfip_copy(key.scanned, p->ptrs.ip_api.get_dst()); + key.scanned.set(*p->ptrs.ip_api.get_dst()); /* ** Get the scanned tracker. @@ -465,12 +468,12 @@ int PortScan::ps_tracker_lookup(PS_PKT* ps_pkt, PS_TRACKER** scanner, */ if (config->detect_scan_type & PS_TYPE_PORTSWEEP) { - sfip_clear(key.scanned); + key.scanned.clear(); if (ps_pkt->reverse_pkt) - sfip_copy(key.scanner, p->ptrs.ip_api.get_dst()); + key.scanner.set(*p->ptrs.ip_api.get_dst()); else - sfip_copy(key.scanner, p->ptrs.ip_api.get_src()); + key.scanner.set(*p->ptrs.ip_api.get_src()); /* ** Get the scanner tracker @@ -613,7 +616,7 @@ int PortScan::ps_proto_update_window(PS_PROTO* proto, time_t pkt_time) ** @param u_short port/ip_proto to track ** @param time_t time the packet was received. update windows. */ -int PortScan::ps_proto_update(PS_PROTO* proto, int ps_cnt, int pri_cnt, const sfip_t* ip, +int PortScan::ps_proto_update(PS_PROTO* proto, int ps_cnt, int pri_cnt, const SfIp* ip, u_short port, time_t pkt_time) { if (!proto) @@ -662,32 +665,32 @@ int PortScan::ps_proto_update(PS_PROTO* proto, int ps_cnt, int pri_cnt, const sf if (proto->connection_count < 0) proto->connection_count = 0; - if (!sfip_unset_equals(&proto->u_ips, ip)) + if (!proto->u_ips.equals(*ip, false)) { proto->u_ip_count++; - sfip_copy(proto->u_ips, ip); + proto->u_ips.set(*ip); } /* we need to do the IP comparisons in host order */ - if (sfip_is_set(&proto->low_ip)) + if (proto->low_ip.is_set()) { - if (sfip_greater(&proto->low_ip, ip)) - sfip_copy(proto->low_ip, ip); + if (proto->low_ip.greater_than(*ip)) + proto->low_ip.set(*ip); } else { - sfip_copy(proto->low_ip, ip); + proto->low_ip.set(*ip); } - if (sfip_is_set(proto->high_ip)) + if (proto->high_ip.is_set()) { - if (sfip_lesser(&proto->high_ip, ip)) - sfip_copy(proto->high_ip, ip); + if (proto->high_ip.less_than(*ip)) + proto->high_ip.set(*ip); } else { - sfip_copy(proto->high_ip, ip); + proto->high_ip.set(*ip); } if (proto->u_ports != port) @@ -762,8 +765,8 @@ int PortScan::ps_tracker_update_tcp(PS_PKT* ps_pkt, PS_TRACKER* scanner, { Packet* p; uint32_t session_flags = 0x0; - sfip_t cleared; - sfip_clear(cleared); + SfIp cleared; + cleared.clear(); p = (Packet*)ps_pkt->pkt; @@ -942,8 +945,8 @@ int PortScan::ps_tracker_update_ip(PS_PKT* ps_pkt, PS_TRACKER* scanner, PS_TRACKER* scanned) { Packet* p; - sfip_t cleared; - sfip_clear(cleared); + SfIp cleared; + cleared.clear(); p = (Packet*)ps_pkt->pkt; @@ -974,8 +977,8 @@ int PortScan::ps_tracker_update_udp(PS_PKT* ps_pkt, PS_TRACKER* scanner, PS_TRACKER* scanned) { Packet* p; - sfip_t cleared; - sfip_clear(cleared); + SfIp cleared; + cleared.clear(); p = (Packet*)ps_pkt->pkt; @@ -1031,8 +1034,8 @@ int PortScan::ps_tracker_update_icmp( PS_PKT* ps_pkt, PS_TRACKER* scanner, PS_TRACKER*) { Packet* p; - sfip_t cleared; - sfip_clear(cleared); + SfIp cleared; + cleared.clear(); p = (Packet*)ps_pkt->pkt; diff --git a/src/network_inspectors/port_scan/ps_detect.h b/src/network_inspectors/port_scan/ps_detect.h index 5da16ac7c..bf8c35768 100644 --- a/src/network_inspectors/port_scan/ps_detect.h +++ b/src/network_inspectors/port_scan/ps_detect.h @@ -24,7 +24,7 @@ #include #include "ipobj.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" #define PS_OPEN_PORTS 8 @@ -67,9 +67,9 @@ struct PS_PROTO unsigned short low_p; unsigned short u_ports; - sfip_t high_ip; - sfip_t low_ip; - sfip_t u_ips; + SfIp high_ip; + SfIp low_ip; + SfIp u_ips; unsigned short open_ports[PS_OPEN_PORTS]; unsigned char open_ports_cnt; diff --git a/src/network_inspectors/port_scan/ps_inspect.h b/src/network_inspectors/port_scan/ps_inspect.h index bc7ed873c..a406f9932 100644 --- a/src/network_inspectors/port_scan/ps_inspect.h +++ b/src/network_inspectors/port_scan/ps_inspect.h @@ -27,7 +27,7 @@ #include "framework/inspector.h" #include "ps_detect.h" -struct sfip_t; +struct SfIp; struct PS_PROTO; struct PS_TRACKER; struct PS_PKT; @@ -51,8 +51,8 @@ private: void ps_parse(SnortConfig*, char*); int ps_ignore_ip( - const sfip_t* scanner, uint16_t scanner_port, - const sfip_t* scanned, uint16_t scanned_port); + const SfIp* scanner, uint16_t scanner_port, + const SfIp* scanned, uint16_t scanned_port); int ps_filter_ignore(PS_PKT* ps_pkt); int ps_tracker_lookup( @@ -62,7 +62,7 @@ private: int ps_proto_update_window(PS_PROTO* proto, time_t pkt_time); int ps_proto_update( - PS_PROTO* proto, int ps_cnt, int pri_cnt, const sfip_t* ip, + PS_PROTO* proto, int ps_cnt, int pri_cnt, const SfIp* ip, u_short port, time_t pkt_time); int ps_tracker_update( diff --git a/src/network_inspectors/reputation/reputation_inspect.cc b/src/network_inspectors/reputation/reputation_inspect.cc index 1348c08f7..a40c227ec 100644 --- a/src/network_inspectors/reputation/reputation_inspect.cc +++ b/src/network_inspectors/reputation/reputation_inspect.cc @@ -166,21 +166,21 @@ static void PrintReputationConf(ReputationConfig* config) LogMessage("\n"); } -static inline IPrepInfo* ReputationLookup(ReputationConfig* config, const sfip_t* ip) +static inline IPrepInfo* ReputationLookup(ReputationConfig* config, const SfIp* ip) { IPrepInfo* result; - DEBUG_WRAP(DebugFormat(DEBUG_REPUTATION, "Lookup address: %s \n",sfip_to_str(ip) ); ); + DEBUG_WRAP(DebugFormat(DEBUG_REPUTATION, "Lookup address: %s \n", ip->ntoa() ); ); if (!config->scanlocal) { - if (sfip_is_private(ip) ) + if (ip->is_private() ) { DEBUG_WRAP(DebugMessage(DEBUG_REPUTATION, "Private address\n"); ); return nullptr; } } - result = (IPrepInfo*)sfrt_flat_dir8x_lookup((void*)ip, config->iplist); + result = (IPrepInfo*)sfrt_flat_dir8x_lookup(ip, config->iplist); return (result); } @@ -229,7 +229,7 @@ static inline IPdecision GetReputation(ReputationConfig* config, IPrepInfo* repI static bool ReputationDecisionPerLayer(ReputationConfig* config, Packet* p, ip::IpApi ip_api, IPdecision* decision_final) { - const sfip_t* ip; + const SfIp* ip; IPdecision decision; IPrepInfo* result; diff --git a/src/network_inspectors/reputation/reputation_parse.cc b/src/network_inspectors/reputation/reputation_parse.cc index bfca10cf9..8094662a6 100644 --- a/src/network_inspectors/reputation/reputation_parse.cc +++ b/src/network_inspectors/reputation/reputation_parse.cc @@ -21,11 +21,14 @@ #include "reputation_parse.h" #include +#include + #include #include "log/messages.h" #include "main/snort_debug.h" #include "parser/config_file.h" +#include "sfip/sf_cidr.h" #include "utils/util.h" using namespace std; @@ -307,7 +310,7 @@ static int64_t updateEntryInfo(INFO* current, INFO new_entry, SaveDest saveDest, return bytesAllocated; } -static int AddIPtoList(sfip_t* ipAddr,INFO ipInfo_ptr, ReputationConfig* config) +static int AddIPtoList(SfCidr* ipAddr,INFO ipInfo_ptr, ReputationConfig* config) { int iRet; int iFinalRet = IP_INSERT_SUCCESS; @@ -317,38 +320,27 @@ static int AddIPtoList(sfip_t* ipAddr,INFO ipInfo_ptr, ReputationConfig* config) uint32_t usageBeforeAdd; uint32_t usageAfterAdd; - if (ipAddr->family == AF_INET) - { - ipAddr->ip32[0] = ntohl(ipAddr->ip32[0]); - } - else if (ipAddr->family == AF_INET6) - { - int i; - for (i = 0; i < 4; i++) - ipAddr->ip32[i] = ntohl(ipAddr->ip32[i]); - } - #ifdef DEBUG_MSGS - if (nullptr != sfrt_flat_lookup((void*)ipAddr, config->iplist)) + if (nullptr != sfrt_flat_lookup(ipAddr->get_addr(), config->iplist)) { - DebugFormat(DEBUG_REPUTATION, "Find address before insert: %s\n", sfip_to_str(ipAddr) ); + DebugFormat(DEBUG_REPUTATION, "Find address before insert: %s\n", ipAddr->ntoa() ); } else { DebugFormat(DEBUG_REPUTATION, - "Can't find address before insert: %s\n", sfip_to_str(ipAddr) ); + "Can't find address before insert: %s\n", ipAddr->ntoa() ); } #endif usageBeforeAdd = sfrt_flat_usage(config->iplist); /*Check whether the same or more generic address is already in the table*/ - if (nullptr != sfrt_flat_lookup((void*)ipAddr, config->iplist)) + if (nullptr != sfrt_flat_lookup(ipAddr->get_addr(), config->iplist)) { iFinalRet = IP_INSERT_DUPLICATE; } - iRet = sfrt_flat_insert((void*)ipAddr, (unsigned char)ipAddr->bits, ipInfo_ptr, RT_FAVOR_ALL, + iRet = sfrt_flat_insert(ipAddr, (unsigned char)ipAddr->get_bits(), ipInfo_ptr, RT_FAVOR_ALL, config->iplist, &updateEntryInfo); DEBUG_WRAP(DebugFormat(DEBUG_REPUTATION, "Unused memory: %zu \n",segment_unusedmem()); ); @@ -359,10 +351,10 @@ static int AddIPtoList(sfip_t* ipAddr,INFO ipInfo_ptr, ReputationConfig* config) DebugFormat(DEBUG_REPUTATION, "Number of entries input: %d, in table: %u \n", totalNumEntries,sfrt_flat_num_entries(config->iplist) ); DebugFormat(DEBUG_REPUTATION, "Memory allocated: %u \n",sfrt_flat_usage(config->iplist) ); - result = (IPrepInfo*)sfrt_flat_lookup((void*)ipAddr, config->iplist); + result = (IPrepInfo*)sfrt_flat_lookup(ipAddr->get_addr(), config->iplist); if (nullptr != result) { - DebugFormat(DEBUG_REPUTATION, "Find address after insert: %s \n",sfip_to_str(ipAddr) ); + DebugFormat(DEBUG_REPUTATION, "Find address after insert: %s \n", ipAddr->ntoa() ); DEBUG_WRAP(ReputationPrintRepInfo(result, (uint8_t*)config->iplist); ); } #endif @@ -372,13 +364,13 @@ static int AddIPtoList(sfip_t* ipAddr,INFO ipInfo_ptr, ReputationConfig* config) { iFinalRet = IP_MEM_ALLOC_FAILURE; DEBUG_WRAP(DebugFormat(DEBUG_REPUTATION, "Insert error: %d for address: %s \n",iRet, - sfip_to_str(ipAddr) ); ); + ipAddr->ntoa() ); ); } else { iFinalRet = IP_INSERT_FAILURE; DEBUG_WRAP(DebugFormat(DEBUG_REPUTATION, "Insert error: %d for address: %s \n",iRet, - sfip_to_str(ipAddr) ); ); + ipAddr->ntoa() ); ); } usageAfterAdd = sfrt_flat_usage(config->iplist); @@ -396,32 +388,24 @@ static int AddIPtoList(sfip_t* ipAddr,INFO ipInfo_ptr, ReputationConfig* config) return iFinalRet; } -static int snort_pton__address(char const* src, sfip_t* dest) +// FIXIT-L X Remove this or at least move it to SfCidr? +static int snort_pton__address(char const* src, SfCidr* dest) { unsigned char _temp[sizeof(struct in6_addr)]; if ( inet_pton(AF_INET, src, _temp) == 1 ) - { - dest->family = AF_INET; - dest->bits = 32; - } + dest->set(_temp, AF_INET); else if ( inet_pton(AF_INET6, src, _temp) == 1 ) - { - dest->family = AF_INET6; - dest->bits = 128; - } + dest->set(_temp, AF_INET6); else - { return 0; - } - - memcpy(&dest->ip8[0], _temp, sizeof(_temp)); return 1; } +// FIXIT-L X Remove this or at least move it to SfCidr? #define isident(x) (isxdigit((x)) || (x) == ':' || (x) == '.') -static int snort_pton(char const* src, sfip_t* dest) +static int snort_pton(char const* src, SfCidr* dest) { char ipbuf[INET6_ADDRSTRLEN]; char cidrbuf[sizeof("128")]; @@ -531,10 +515,13 @@ static int snort_pton(char const* src, sfip_t* dest) char* end; int value = strtol(cidrbuf, &end, 10); - if ( value > dest->bits || value <= 0 || errno == ERANGE ) + if ( value > dest->get_bits() || value <= 0 || errno == ERANGE ) return 0; - dest->bits = value; + if (dest->get_addr()->is_ip4() && value <= 32) + dest->set_bits(value + 96); + else + dest->set_bits(value); } return 1; @@ -542,7 +529,7 @@ static int snort_pton(char const* src, sfip_t* dest) static int ProcessLine(char* line, INFO info, ReputationConfig* config) { - sfip_t address; + SfCidr address; if ( !line || *line == '\0' ) return IP_INSERT_SUCCESS; diff --git a/src/packet_io/intf.cc b/src/packet_io/intf.cc index 11ed388a3..9b200448d 100644 --- a/src/packet_io/intf.cc +++ b/src/packet_io/intf.cc @@ -19,6 +19,7 @@ #include "intf.h" +#include #include #include @@ -56,9 +57,9 @@ void PrintAllInterfaces() struct sockaddr_in* saddr = (struct sockaddr_in*)dev->addresses->addr; if ((saddr->sin_family == AF_INET) || (saddr->sin_family == AF_INET6)) { - sfip_t dev_ip; - sfip_set_raw(&dev_ip, &saddr->sin_addr, saddr->sin_family); - printf("\t%s", inet_ntoa(&dev_ip)); + SfIp dev_ip; + dev_ip.set(&saddr->sin_addr, saddr->sin_family); + printf("\t%s", dev_ip.ntoa()); } else printf("\tdisabled"); diff --git a/src/packet_io/sfdaq.cc b/src/packet_io/sfdaq.cc index 04c44edc1..189a5f831 100644 --- a/src/packet_io/sfdaq.cc +++ b/src/packet_io/sfdaq.cc @@ -38,6 +38,7 @@ extern "C" { #include "log/messages.h" #include "main/snort_config.h" #include "parser/parser.h" +#include "protocols/packet.h" #include "protocols/vlan.h" #include "utils/util.h" @@ -548,24 +549,24 @@ int SFDAQInstance::modify_flow_opaque(const DAQ_PktHdr_t* hdr, uint32_t opaque) } // FIXIT-L X Add Snort flag defitions for callers to use and translate/pass them through to the DAQ module -int SFDAQInstance::add_expected(const Packet* ctrlPkt, const sfip_t* cliIP, uint16_t cliPort, - const sfip_t* srvIP, uint16_t srvPort, IpProtocol protocol, unsigned timeout_ms, unsigned /* flags */) +int SFDAQInstance::add_expected(const Packet* ctrlPkt, const SfIp* cliIP, uint16_t cliPort, + const SfIp* srvIP, uint16_t srvPort, IpProtocol protocol, unsigned timeout_ms, unsigned /* flags */) { DAQ_Data_Channel_Params_t daq_params; DAQ_DP_key_t dp_key; - dp_key.src_af = cliIP->family; + dp_key.src_af = cliIP->get_family(); if (cliIP->is_ip4()) - dp_key.sa.src_ip4.s_addr = *cliIP->ip32; + dp_key.sa.src_ip4.s_addr = cliIP->get_ip4_value(); else - memcpy(&dp_key.sa.src_ip6, cliIP->ip8, sizeof(dp_key.sa.src_ip6)); + memcpy(&dp_key.sa.src_ip6, cliIP->get_ip6_ptr(), sizeof(dp_key.sa.src_ip6)); dp_key.src_port = cliPort; - dp_key.dst_af = srvIP->family; + dp_key.dst_af = srvIP->get_family(); if (srvIP->is_ip4()) - dp_key.da.dst_ip4.s_addr = *srvIP->ip32; + dp_key.da.dst_ip4.s_addr = srvIP->get_ip4_value(); else - memcpy(&dp_key.da.dst_ip6, srvIP->ip8, sizeof(dp_key.da.dst_ip6)); + memcpy(&dp_key.da.dst_ip6, srvIP->get_ip6_ptr(), sizeof(dp_key.da.dst_ip6)); dp_key.dst_port = srvPort; dp_key.protocol = (uint8_t) protocol; diff --git a/src/packet_io/sfdaq.h b/src/packet_io/sfdaq.h index 7629e46c8..5c3ef2835 100644 --- a/src/packet_io/sfdaq.h +++ b/src/packet_io/sfdaq.h @@ -33,7 +33,7 @@ extern "C" { struct Packet; struct SnortConfig; -struct sfip_t; +struct SfIp; class SFDAQInstance { @@ -58,8 +58,8 @@ public: bool break_loop(int error); const DAQ_Stats_t* get_stats(); int modify_flow_opaque(const DAQ_PktHdr_t*, uint32_t opaque); - int add_expected(const Packet* ctrlPkt, const sfip_t* cliIP, uint16_t cliPort, - const sfip_t* srvIP, uint16_t srvPort, IpProtocol, unsigned timeout_ms, + int add_expected(const Packet* ctrlPkt, const SfIp* cliIP, uint16_t cliPort, + const SfIp* srvIP, uint16_t srvPort, IpProtocol, unsigned timeout_ms, unsigned /* flags */); private: bool set_filter(const char*); diff --git a/src/packet_io/trough.cc b/src/packet_io/trough.cc index f81bd54b1..2dfec97bc 100644 --- a/src/packet_io/trough.cc +++ b/src/packet_io/trough.cc @@ -21,6 +21,7 @@ #include #include +#include #include #include @@ -28,6 +29,7 @@ #include "helpers/directory.h" #include "log/messages.h" #include "main/snort_config.h" +#include "utils/util.h" std::vector Trough::pcap_object_list; std::vector Trough::pcap_queue; diff --git a/src/parser/config_file.cc b/src/parser/config_file.cc index aa92bdf19..05beda7e1 100644 --- a/src/parser/config_file.cc +++ b/src/parser/config_file.cc @@ -308,7 +308,7 @@ void ConfigObfuscationMask(SnortConfig* sc, const char* args) sc->output_flags |= OUTPUT_FLAG__OBFUSCATE; - sfip_pton(args, &sc->obfuscation_net); + sc->obfuscation_net.set(args); } void ConfigQuiet(SnortConfig* sc, const char*) diff --git a/src/parser/vars.cc b/src/parser/vars.cc index 07a0323cf..850c6c4b0 100644 --- a/src/parser/vars.cc +++ b/src/parser/vars.cc @@ -505,7 +505,7 @@ VarEntry* VarDefine( if (VarIsIpList(ip_vartable, value)) { - SFIP_RET ret; + SfIpRet ret; if (ip_vartable == NULL) return NULL; diff --git a/src/protocols/ip.cc b/src/protocols/ip.cc index 3e136f623..19483cb28 100644 --- a/src/protocols/ip.cc +++ b/src/protocols/ip.cc @@ -37,15 +37,8 @@ void IpApi::set(const IP4Hdr* h4) iph = (const void*)h4; type = IAT_4; - src.family = AF_INET; - src.bits = 32; - src.ip32[0] = *(uint32_t*)(&h4->ip_src); - std::memset(&(src.ip32[1]), 0, 12); - - dst.family = AF_INET; - dst.bits = 32; - dst.ip32[0] = *(uint32_t*)(&h4->ip_dst); - std::memset(&(dst.ip32[1]), 0, 12); + src.set(&h4->ip_src, AF_INET); + dst.set(&h4->ip_dst, AF_INET); } void IpApi::set(const ip::IP6Hdr* h6) @@ -53,20 +46,15 @@ void IpApi::set(const ip::IP6Hdr* h6) iph = (const void*)h6; type = IAT_6; - src.family = AF_INET6; - src.bits = 128; - std::memcpy(&(src.ip8), &(h6->ip6_src), 16); - - dst.family = AF_INET6; - dst.bits = 128; - std::memcpy(&(dst.ip8), &(h6->ip6_dst), 16); + src.set(&h6->ip6_src, AF_INET6); + dst.set(&h6->ip6_dst, AF_INET6); } -void IpApi::set(const sfip_t& sip, const sfip_t& dip) +void IpApi::set(const SfIp& sip, const SfIp& dip) { type = IAT_DATA; - sfip_set_ip(&src, &sip); - sfip_set_ip(&dst, &dip); + src.set(sip); + dst.set(dip); iph = nullptr; } diff --git a/src/protocols/ip.h b/src/protocols/ip.h index 014e16659..e651da3af 100644 --- a/src/protocols/ip.h +++ b/src/protocols/ip.h @@ -29,10 +29,10 @@ #include #include +#include "main/snort_types.h" #include "protocols/ipv4.h" #include "protocols/ipv6.h" -#include "sfip/sfip_t.h" -#include "main/snort_types.h" +#include "sfip/sf_ip.h" struct Packet; @@ -54,7 +54,7 @@ public: void set(const IP4Hdr* h4); void set(const IP6Hdr* h6); - void set(const sfip_t& src, const sfip_t& dst); + void set(const SfIp& src, const SfIp& dst); bool set(const uint8_t* raw_ip_data); void reset(); @@ -102,10 +102,10 @@ public: inline const IP6Hdr* get_ip6h() const { return (type == IAT_6) ? (IP6Hdr*)iph : nullptr; } - inline const sfip_t* get_src() const + inline const SfIp* get_src() const { return (type != IAT_NONE) ? &src : nullptr; } - inline const sfip_t* get_dst() const + inline const SfIp* get_dst() const { return (type != IAT_NONE) ? &dst : nullptr; } // only relevant to IP4 @@ -130,8 +130,8 @@ public: uint8_t ver() const; private: - sfip_t src; - sfip_t dst; + SfIp src; + SfIp dst; const void* iph; Type type; }; diff --git a/src/protocols/ipv6.h b/src/protocols/ipv6.h index 517c9c9c3..e6f7e7596 100644 --- a/src/protocols/ipv6.h +++ b/src/protocols/ipv6.h @@ -30,7 +30,6 @@ #include #include -#include "sfip/sfip_t.h" #include "protocols/protocol_ids.h" namespace ip diff --git a/src/pub_sub/sip_events.cc b/src/pub_sub/sip_events.cc index 8c96ad7e9..7c8d48e18 100644 --- a/src/pub_sub/sip_events.cc +++ b/src/pub_sub/sip_events.cc @@ -104,7 +104,7 @@ SipEventMediaData* SipEventMediaSession::next_media_data() } -const sfip_t* SipEventMediaData::get_address() const +const SfIp* SipEventMediaData::get_address() const { return &data->maddress; } uint16_t SipEventMediaData::get_port() const diff --git a/src/pub_sub/sip_events.h b/src/pub_sub/sip_events.h index 1f0c46e70..7cd2bcc20 100644 --- a/src/pub_sub/sip_events.h +++ b/src/pub_sub/sip_events.h @@ -46,7 +46,7 @@ public: SipEventMediaData(SIP_MediaData* data) { this->data = data; } - const sfip_t* get_address() const; + const SfIp* get_address() const; uint16_t get_port() const; private: diff --git a/src/service_inspectors/dce_rpc/dce_smb2.cc b/src/service_inspectors/dce_rpc/dce_smb2.cc index 0aff359b3..93a10f528 100644 --- a/src/service_inspectors/dce_rpc/dce_smb2.cc +++ b/src/service_inspectors/dce_rpc/dce_smb2.cc @@ -23,6 +23,7 @@ #include "detection/detection_util.h" #include "file_api/file_flows.h" +#include "utils/util.h" #include "dce_smb_module.h" #include "dce_smb_utils.h" diff --git a/src/service_inspectors/dce_rpc/dce_smb_module.cc b/src/service_inspectors/dce_rpc/dce_smb_module.cc index 1ee6b3ec1..9c68fca06 100644 --- a/src/service_inspectors/dce_rpc/dce_smb_module.cc +++ b/src/service_inspectors/dce_rpc/dce_smb_module.cc @@ -22,6 +22,7 @@ #include "log/messages.h" #include "main/snort_config.h" +#include "utils/util.h" #include "dce_smb.h" diff --git a/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.cc b/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.cc index 1cbdfde7b..eb43d2793 100644 --- a/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.cc +++ b/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.cc @@ -116,7 +116,7 @@ int ftp_bounce_lookup_cleanup(BOUNCE_LOOKUP** BounceLookup) * */ int ftp_bounce_lookup_add(BOUNCE_LOOKUP* BounceLookup, - const sfip_t* Ip, FTP_BOUNCE_TO* BounceTo) + const SfIp* Ip, FTP_BOUNCE_TO* BounceTo) { int iRet; @@ -125,7 +125,7 @@ int ftp_bounce_lookup_add(BOUNCE_LOOKUP* BounceLookup, return FTPP_INVALID_ARG; } - iRet = KMapAdd(BounceLookup, (void*)Ip, Ip->sfip_size(), (void*)BounceTo); + iRet = KMapAdd(BounceLookup, (void*)Ip, sizeof(*Ip), (void*)BounceTo); if (iRet) { @@ -147,7 +147,7 @@ int ftp_bounce_lookup_add(BOUNCE_LOOKUP* BounceLookup, /* * Function: ftp_bounce_lookup_find(BOUNCE_LOOKUP *BounceLookup, - * const sfip_t *ip, int *iError) + * const SfIp *ip, int *iError) * * Purpose: Find a bounce configuration given a IP. * We look up a bounce configuration given an IP and @@ -164,7 +164,7 @@ int ftp_bounce_lookup_add(BOUNCE_LOOKUP* BounceLookup, * */ FTP_BOUNCE_TO* ftp_bounce_lookup_find( - BOUNCE_LOOKUP* BounceLookup, const sfip_t* Ip, int* iError) + BOUNCE_LOOKUP* BounceLookup, const SfIp* Ip, int* iError) { FTP_BOUNCE_TO* BounceTo = NULL; @@ -181,7 +181,7 @@ FTP_BOUNCE_TO* ftp_bounce_lookup_find( *iError = FTPP_SUCCESS; - BounceTo = (FTP_BOUNCE_TO*)KMapFind(BounceLookup, (void*)Ip, Ip->sfip_size()); + BounceTo = (FTP_BOUNCE_TO*)KMapFind(BounceLookup, (void*)Ip, sizeof(*Ip)); if (!BounceTo) { *iError = FTPP_NOT_FOUND; diff --git a/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.h b/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.h index 969ac5e9d..3fac827f2 100644 --- a/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.h +++ b/src/service_inspectors/ftp_telnet/ftp_bounce_lookup.h @@ -36,9 +36,9 @@ int ftp_bounce_lookup_init(BOUNCE_LOOKUP** BounceLookup); int ftp_bounce_lookup_cleanup(BOUNCE_LOOKUP** BounceLookup); -int ftp_bounce_lookup_add(BOUNCE_LOOKUP* BounceLookup, const sfip_t* ip, FTP_BOUNCE_TO* BounceTo); +int ftp_bounce_lookup_add(BOUNCE_LOOKUP* BounceLookup, const SfIp* ip, FTP_BOUNCE_TO* BounceTo); -FTP_BOUNCE_TO* ftp_bounce_lookup_find(BOUNCE_LOOKUP* BounceLookup, const sfip_t* ip, int* iError); +FTP_BOUNCE_TO* ftp_bounce_lookup_find(BOUNCE_LOOKUP* BounceLookup, const SfIp* ip, int* iError); // FIXIT-L orphan code until FTP client inspector acquires a show() method // FTP_BOUNCE_TO* ftp_bounce_lookup_first(BOUNCE_LOOKUP* BounceLookup, int* iError); // FTP_BOUNCE_TO* ftp_bounce_lookup_next(BOUNCE_LOOKUP* BounceLookup, int* iError); diff --git a/src/service_inspectors/ftp_telnet/ftp_parse.cc b/src/service_inspectors/ftp_telnet/ftp_parse.cc index f9c796165..279a9338f 100644 --- a/src/service_inspectors/ftp_telnet/ftp_parse.cc +++ b/src/service_inspectors/ftp_telnet/ftp_parse.cc @@ -655,7 +655,7 @@ int ProcessFTPAllowBounce( FTP_BOUNCE_TO* newBounce = (FTP_BOUNCE_TO*)snort_calloc(sizeof(FTP_BOUNCE_TO)); - sfip_set_raw(&newBounce->ip, addr, len == 4 ? AF_INET : AF_INET6); + newBounce->ip.set(addr, len == 4 ? AF_INET : AF_INET6); newBounce->portlo = low; newBounce->porthi = high; diff --git a/src/service_inspectors/ftp_telnet/ftp_print.cc b/src/service_inspectors/ftp_telnet/ftp_print.cc index 34273ecb9..c1f7b8b79 100644 --- a/src/service_inspectors/ftp_telnet/ftp_print.cc +++ b/src/service_inspectors/ftp_telnet/ftp_print.cc @@ -195,7 +195,7 @@ int PrintFTPClientConf(FTP_CLIENT_PROTO_CONF* ClientConf) uint8_t bits; bits_str[0] = '\0'; - addr_str = sfip_to_str(&FTPBounce->ip); + addr_str = FTPBounce->ip.ntoa(); bits = (uint8_t)FTPBounce->ip.bits; if (((FTPBounce->ip.family == AF_INET) && (bits != 32)) || ((FTPBounce->ip.family == AF_INET6) && (bits != 128))) diff --git a/src/service_inspectors/ftp_telnet/ftpp_si.cc b/src/service_inspectors/ftp_telnet/ftpp_si.cc index 7c27934db..53a40a748 100644 --- a/src/service_inspectors/ftp_telnet/ftpp_si.cc +++ b/src/service_inspectors/ftp_telnet/ftpp_si.cc @@ -378,9 +378,9 @@ static inline int FTPResetsession(FTP_SESSION* Ftpsession) Ftpsession->server_conf = NULL; Ftpsession->encr_state = NO_STATE; - sfip_clear(Ftpsession->clientIP); + Ftpsession->clientIP.clear(); Ftpsession->clientPort = 0; - sfip_clear(Ftpsession->serverIP); + Ftpsession->serverIP.clear(); Ftpsession->serverPort = 0; Ftpsession->data_chan_state = NO_STATE; Ftpsession->data_chan_index = -1; @@ -486,8 +486,8 @@ int FTPsessionInspection( */ int SetSiInput(FTPP_SI_INPUT* SiInput, Packet* p) { - sfip_copy(SiInput->sip, p->ptrs.ip_api.get_src()); - sfip_copy(SiInput->dip, p->ptrs.ip_api.get_dst()); + SiInput->sip.set(*p->ptrs.ip_api.get_src()); + SiInput->dip.set(*p->ptrs.ip_api.get_dst()); SiInput->sport = p->ptrs.sp; SiInput->dport = p->ptrs.dp; diff --git a/src/service_inspectors/ftp_telnet/ftpp_si.h b/src/service_inspectors/ftp_telnet/ftpp_si.h index fab6e4f6c..8b832b128 100644 --- a/src/service_inspectors/ftp_telnet/ftpp_si.h +++ b/src/service_inspectors/ftp_telnet/ftpp_si.h @@ -162,9 +162,9 @@ struct FTP_SESSION int data_chan_index; int data_xfer_index; bool data_xfer_dir; - sfip_t clientIP; + SfIp clientIP; uint16_t clientPort; - sfip_t serverIP; + SfIp serverIP; uint16_t serverPort; /* A file is being transfered on ftp-data channel */ @@ -250,8 +250,8 @@ public: */ struct FTPP_SI_INPUT { - sfip_t sip; - sfip_t dip; + SfIp sip; + SfIp dip; unsigned short sport; unsigned short dport; unsigned char pdir; diff --git a/src/service_inspectors/ftp_telnet/ftpp_ui_config.h b/src/service_inspectors/ftp_telnet/ftpp_ui_config.h index d1a576b29..f40cccd63 100644 --- a/src/service_inspectors/ftp_telnet/ftpp_ui_config.h +++ b/src/service_inspectors/ftp_telnet/ftpp_ui_config.h @@ -39,7 +39,7 @@ #define FTPP_UI_CONFIG_H #include "framework/bits.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" #include "sfrt/sfrt.h" #include "utils/kmap.h" @@ -198,7 +198,7 @@ struct FTP_SERVER_PROTO_CONF typedef struct s_FTP_BOUNCE_TO { - sfip_t ip; + SfIp ip; int relevant_bits; unsigned short portlo; unsigned short porthi; diff --git a/src/service_inspectors/ftp_telnet/pp_ftp.cc b/src/service_inspectors/ftp_telnet/pp_ftp.cc index 775fe16b4..3a8f0667a 100644 --- a/src/service_inspectors/ftp_telnet/pp_ftp.cc +++ b/src/service_inspectors/ftp_telnet/pp_ftp.cc @@ -40,6 +40,11 @@ #include "config.h" #endif +#include "detection/detection_util.h" +#include "file_api/file_service.h" +#include "sfip/sf_ip.h" +#include "utils/util.h" + #include "ft_main.h" #include "ftp_bounce_lookup.h" #include "ftp_cmd_lookup.h" @@ -47,10 +52,6 @@ #include "ftpp_return_codes.h" #include "pp_telnet.h" -#include "detection/detection_util.h" -#include "file_api/file_service.h" -#include "sfip/sf_ip.h" - #ifndef MAXHOSTNAMELEN /* Why doesn't Windows define this? */ #define MAXHOSTNAMELEN 256 #endif @@ -86,7 +87,7 @@ static THREAD_LOCAL int ftp_cmd_pipe_index = 0; */ static int getIP959( const char** ip_start, const char* last_char, const char* term_char, - sfip_t* ipRet, uint16_t* portRet + SfIp* ipRet, uint16_t* portRet ) { uint32_t ip=0; @@ -133,7 +134,7 @@ static int getIP959( } ip = htonl(ip); - sfip_set_raw(ipRet, &ip, AF_INET); + ipRet->set(&ip, AF_INET); *portRet = port; *ip_start = this_param; @@ -160,7 +161,7 @@ static int getIP959( */ static int getIP1639( const char** ip_start, const char* last_char, const char*, - sfip_t* ipRet, uint16_t* portRet + SfIp* ipRet, uint16_t* portRet ) { char bytes[21]; /* max of 1+5+3 and 1+17+3 */ @@ -198,10 +199,10 @@ static int getIP1639( int n; for ( n = 0; n < 4; n++ ) ip4_addr = (ip4_addr << 8) | bytes[n+2]; - /* don't call sfip_set_raw() on raw bytes + /* don't call sfip set() on raw bytes to avoid possible word alignment issues */ ip4_addr = htonl(ip4_addr); - sfip_set_raw(ipRet, (void*)&ip4_addr, AF_INET); + ipRet->set((void*)&ip4_addr, AF_INET); } *portRet = (bytes[7] << 8) | bytes[8]; break; @@ -210,7 +211,7 @@ static int getIP1639( if ( nBytes != 21 || bytes[1] != 16 || bytes[18] != 2 ) return FTPP_INVALID_ARG; - sfip_set_raw(ipRet, bytes+2, AF_INET6); + ipRet->set(bytes+2, AF_INET6); *portRet = (bytes[19] << 8) | bytes[20]; break; default: @@ -275,7 +276,7 @@ static void CopyField( static int getIP2428( const char** ip_start, const char* last_char, const char*, - sfip_t* ipRet, uint16_t* portRet, FTP_PARAM_TYPE ftyp + SfIp* ipRet, uint16_t* portRet, FTP_PARAM_TYPE ftyp ) { const char* tok = *ip_start; @@ -284,7 +285,7 @@ static int getIP2428( int family = AF_UNSPEC, port = 0; char buf[64]; - sfip_clear((*ipRet)); + ipRet->clear(); *portRet = 0; /* check first delimiter */ @@ -313,7 +314,7 @@ static int getIP2428( case 2: /* check address */ CopyField(buf, tok, sizeof(buf), last_char, delim); - if ( sfip_pton(buf, ipRet) != SFIP_SUCCESS || family != ipRet->family ) + if ( ipRet->set(buf) != SFIP_SUCCESS || family != ipRet->get_family() ) return FTPP_INVALID_ARG; fieldMask |= 2; @@ -355,7 +356,7 @@ static int getIP2428( static int getFTPip( FTP_PARAM_TYPE ftyp, const char** ip_start, const char* last_char, - const char* term_char, sfip_t* ipRet, uint16_t* portRet + const char* term_char, SfIp* ipRet, uint16_t* portRet ) { if ( ftyp == e_host_port ) @@ -691,7 +692,7 @@ static int validate_param(Packet* p, case e_long_host_port: /* LPRT: af,hal,h1,h2,h3,h4...,pal,p1,p2... */ case e_extd_host_port: /* EPRT: |||| */ { - sfip_t ipAddr; + SfIp ipAddr; uint16_t port=0; int ret = getFTPip( @@ -710,7 +711,7 @@ static int validate_param(Packet* p, return FTPP_INVALID_PARAM; } - if ( ThisFmt->type == e_extd_host_port && !sfip_is_set(ipAddr) ) + if ( ThisFmt->type == e_extd_host_port && !ipAddr.is_set() ) { // actually, we expect no addr in 229 responses, which is // understood to be server address, so we set that here @@ -718,7 +719,7 @@ static int validate_param(Packet* p, } if ( session->client_conf->bounce ) { - if (!sfip_equals(&ipAddr, p->ptrs.ip_api.get_src())) + if (!ipAddr.equals(*p->ptrs.ip_api.get_src())) { int alert = 1; @@ -767,7 +768,7 @@ static int validate_param(Packet* p, session->data_chan_state &= ~DATA_CHAN_PASV_CMD_ISSUED; } - sfip_clear(session->serverIP); + session->serverIP.clear(); session->serverPort = 0; } break; @@ -1009,10 +1010,10 @@ static int do_stateful_checks(FTP_SESSION* session, Packet* p, if ( rsp_code >= 227 && rsp_code <= 229 ) { - sfip_t ipAddr; + SfIp ipAddr; uint16_t port=0; const char* ip_begin = req->param_begin; - sfip_clear(ipAddr); + ipAddr.clear(); session->data_chan_state &= ~DATA_CHAN_PASV_CMD_ISSUED; session->data_chan_state |= DATA_CHAN_PASV_CMD_ACCEPT; session->data_chan_index = -1; @@ -1048,14 +1049,14 @@ static int do_stateful_checks(FTP_SESSION* session, Packet* p, ); if (iRet == FTPP_SUCCESS) { - if (!sfip_is_set(ipAddr)) - sfip_copy(session->serverIP, p->ptrs.ip_api.get_src()); + if (!ipAddr.is_set()) + session->serverIP.set(*p->ptrs.ip_api.get_src()); else { session->serverIP = ipAddr; } session->serverPort = port; - sfip_copy(session->clientIP, p->ptrs.ip_api.get_dst()); + session->clientIP.set(*p->ptrs.ip_api.get_dst()); session->clientPort = 0; if ((FileService::get_max_file_depth() > 0) || @@ -1120,13 +1121,13 @@ static int do_stateful_checks(FTP_SESSION* session, Packet* p, session->data_chan_state &= ~DATA_CHAN_PORT_CMD_ISSUED; session->data_chan_state |= DATA_CHAN_PORT_CMD_ACCEPT; session->data_chan_index = -1; - if (sfip_is_set(session->clientIP)) + if (session->clientIP.is_set()) { /* This means we're not in passive mode. */ /* Server is listening/sending from its own IP, * FTP Port -1 */ /* Client IP, Port specified via PORT command */ - sfip_copy(session->serverIP, p->ptrs.ip_api.get_src()); + session->serverIP.set(*p->ptrs.ip_api.get_src()); /* Can't necessarily guarantee this, especially * in the case of a proxy'd connection where the @@ -1216,8 +1217,8 @@ static int do_stateful_checks(FTP_SESSION* session, Packet* p, } /* Clear the session info for next transfer --> * reset host/port */ - sfip_clear(session->serverIP); - sfip_clear(session->clientIP); + session->serverIP.clear(); + session->clientIP.clear(); session->serverPort = session->clientPort = 0; session->datassn = nullptr; diff --git a/src/service_inspectors/sip/sip_common.h b/src/service_inspectors/sip/sip_common.h index 84d0b13b1..34d4ce4cd 100644 --- a/src/service_inspectors/sip/sip_common.h +++ b/src/service_inspectors/sip/sip_common.h @@ -77,7 +77,7 @@ enum SIP_DialogState struct SIP_MediaData { - sfip_t maddress; // media IP + SfIp maddress; // media IP uint16_t mport; // media port uint8_t numPort; // number of media ports SIP_MediaData* nextM; @@ -91,7 +91,7 @@ struct SIP_MediaSession int savedFlag; // whether this data has been saved by a dialog, // if savedFlag = 1, this session will be deleted after sip message is // processed. - sfip_t maddress_default; // Default media IP + SfIp maddress_default; // Default media IP SIP_MediaDataList medias; // Media list in the session SIP_MediaSession* nextS; // Next media session }; diff --git a/src/service_inspectors/sip/sip_dialog.cc b/src/service_inspectors/sip/sip_dialog.cc index 4b845bc54..170fd723e 100644 --- a/src/service_inspectors/sip/sip_dialog.cc +++ b/src/service_inspectors/sip/sip_dialog.cc @@ -35,6 +35,7 @@ #include "protocols/vlan.h" #include "sfip/sf_ip.h" #include "stream/stream.h" +#include "utils/util.h" #include "sip_module.h" #include "sip.h" @@ -407,9 +408,9 @@ static int SIP_ignoreChannels(SIP_DialogData* dialog, Packet* p, SIP_PROTO_CONF* { //void *ssn; DebugFormat(DEBUG_SIP, "Ignoring channels Source IP: %s Port: %hu\n", - sfip_to_str(&mdataA->maddress), mdataA->mport); + mdataA->maddress.ntoa(), mdataA->mport); DebugFormat(DEBUG_SIP, "Ignoring channels Destine IP: %s Port: %hu\n", - sfip_to_str(&mdataB->maddress), mdataB->mport); + mdataB->maddress.ntoa(), mdataB->mport); /* Call into Streams to mark data channel as something to ignore. */ Flow* ssn = Stream::get_flow( @@ -458,7 +459,7 @@ static int SIP_compareMedias(SIP_MediaDataList mlistA, SIP_MediaDataList mlistB) DebugMessage(DEBUG_SIP, "Compare the media data \n"); while ((NULL != mdataA) && (NULL != mdataB)) { - if (sfip_compare(&mdataA->maddress, &mdataB->maddress) != SFIP_EQUAL) + if (mdataA->maddress.compare(mdataB->maddress) != SFIP_EQUAL) break; if ((mdataA->mport != mdataB->mport)|| (mdataA->numPort != mdataB->numPort)) break; @@ -551,7 +552,7 @@ void SIP_displayMedias(SIP_MediaList* dList) while (NULL != mdata) { DebugFormat(DEBUG_SIP, "Media IP: %s, port: %hu, number of ports %hhu\n", - sfip_to_str(&mdata->maddress), mdata->mport, mdata->numPort); + mdata->maddress.ntoa(), mdata->mport, mdata->numPort); mdata = mdata->nextM; } currSession = currSession->nextS; diff --git a/src/service_inspectors/sip/sip_parser.cc b/src/service_inspectors/sip/sip_parser.cc index 1657bdc15..f6c5a906e 100644 --- a/src/service_inspectors/sip/sip_parser.cc +++ b/src/service_inspectors/sip/sip_parser.cc @@ -23,13 +23,13 @@ #include "config.h" #endif -#ifndef HAVE_PARSER_H #include #include "main/snort_types.h" #include "main/snort_debug.h" #include "main/snort_config.h" #include "sfip/sf_ip.h" +#include "utils/util.h" #include "sip_parser.h" #include "sip_config.h" @@ -795,7 +795,7 @@ static int sip_parse_to(SIPMsg* msg, const char* start, const char* end, SIP_PRO static inline bool is_valid_ip(const char *start, int length) { - sfip_t ip; + SfIp ip; char ipStr[INET6_ADDRSTRLEN]; /*Get the IP address*/ @@ -808,7 +808,7 @@ static inline bool is_valid_ip(const char *start, int length) DebugFormat(DEBUG_SIP, "IP data: %s\n", ipStr); - if( (sfip_pton(ipStr, &ip)) != SFIP_SUCCESS) + if( ip.set(ipStr) != SFIP_SUCCESS) { DebugMessage(DEBUG_SIP, "Not valid IP! \n"); return false; @@ -1149,7 +1149,7 @@ static int sip_parse_sdp_o(SIPMsg* msg, const char* start, const char* end) static int sip_parse_sdp_c(SIPMsg* msg, const char* start, const char* end) { int length; - sfip_t* ip; + SfIp* ip; char ipStr[INET6_ADDRSTRLEN + 5]; /* Enough for IPv4 plus netmask or full IPv6 plus prefix */ char* spaceIndex = NULL; @@ -1186,12 +1186,12 @@ static int sip_parse_sdp_c(SIPMsg* msg, const char* start, const char* end) { ip = &(msg->mediaSession->medias->maddress); } - if ( (sfip_pton(ipStr, ip)) != SFIP_SUCCESS) + if ( ip->set(ipStr) != SFIP_SUCCESS) { DebugMessage(DEBUG_SIP, "Parsed error! \n"); return SIP_PARSE_ERROR; } - DebugFormat(DEBUG_SIP, "Parsed Connection data: %s\n", sfip_to_str (ip)); + DebugFormat(DEBUG_SIP, "Parsed Connection data: %s\n", ip->ntoa()); return SIP_PARSE_SUCCESS; } @@ -1236,7 +1236,7 @@ static int sip_parse_sdp_m(SIPMsg* msg, const char* start, const char* end) mdata->maddress = msg->mediaSession->maddress_default; msg->mediaSession->medias = mdata; DebugFormat(DEBUG_SIP, "Media IP: %s, Media port %hu, number of media: %d\n", - sfip_to_str(&mdata->maddress), mdata->mport, mdata->numPort); + mdata->maddress.ntoa(), mdata->mport, mdata->numPort); return SIP_PARSE_SUCCESS; } @@ -1378,7 +1378,7 @@ void sip_freeMediaSession(SIP_MediaSession* mediaSession) while (NULL != curNode) { DebugFormat(DEBUG_SIP, "Clear media ip: %s, port: %d, number of port: %d\n", - sfip_to_str(&curNode->maddress), curNode->mport, curNode->numPort); + curNode->maddress.ntoa(), curNode->mport, curNode->numPort); nextNode = curNode->nextM; snort_free(curNode); curNode = nextNode; @@ -1407,12 +1407,10 @@ void sip_freeMediaList(SIP_MediaList medias) while (NULL != curNode) { DebugFormat(DEBUG_SIP, "Clean Media session default IP: %s, session ID: %u\n", - sfip_to_str(&curNode->maddress_default), curNode->sessionID); + curNode->maddress_default.ntoa(), curNode->sessionID); nextNode = curNode->nextS; sip_freeMediaSession(curNode); curNode = nextNode; } } -#endif - diff --git a/src/service_inspectors/smtp/smtp.cc b/src/service_inspectors/smtp/smtp.cc index e2e38ceab..452349137 100644 --- a/src/service_inspectors/smtp/smtp.cc +++ b/src/service_inspectors/smtp/smtp.cc @@ -40,6 +40,7 @@ #include "log/unified2.h" #include "detection/detection_util.h" #include "utils/safec.h" +#include "utils/util.h" #include "smtp_module.h" #include "smtp_paf.h" diff --git a/src/service_inspectors/smtp/smtp_module.cc b/src/service_inspectors/smtp/smtp_module.cc index 898e930c1..567a0ab17 100644 --- a/src/service_inspectors/smtp/smtp_module.cc +++ b/src/service_inspectors/smtp/smtp_module.cc @@ -25,6 +25,7 @@ #include "log/messages.h" #include "main/snort_config.h" +#include "utils/util.h" using namespace std; diff --git a/src/sfip/CMakeLists.txt b/src/sfip/CMakeLists.txt index 329a58cdf..873435e41 100644 --- a/src/sfip/CMakeLists.txt +++ b/src/sfip/CMakeLists.txt @@ -1,9 +1,9 @@ set(SFIP_INCLUDES - sf_returns.h + sf_cidr.h sf_ip.h sf_ipvar.h - sfip_t.h + sf_returns.h ) if ( ENABLE_UNIT_TESTS ) @@ -13,6 +13,7 @@ endif() add_library ( sfip STATIC ${SFIP_INCLUDES} ${TEST_FILES} + sf_cidr.cc sf_ip.cc sf_ipvar.cc sf_vartable.cc diff --git a/src/sfip/Makefile.am b/src/sfip/Makefile.am index ce64ad78c..be0c98be5 100644 --- a/src/sfip/Makefile.am +++ b/src/sfip/Makefile.am @@ -5,11 +5,12 @@ x_includedir = $(pkgincludedir)/sfip x_include_HEADERS = \ sf_returns.h \ +sf_cidr.h \ sf_ip.h \ -sf_ipvar.h \ -sfip_t.h +sf_ipvar.h libsfip_a_SOURCES = \ +sf_cidr.cc \ sf_ip.cc \ sf_ipvar.cc \ sf_vartable.cc \ diff --git a/src/sfip/sf_cidr.cc b/src/sfip/sf_cidr.cc new file mode 100644 index 000000000..0aa73fdb9 --- /dev/null +++ b/src/sfip/sf_cidr.cc @@ -0,0 +1,69 @@ +//-------------------------------------------------------------------------- +// Copyright (C) 2014-2016 Cisco and/or its affiliates. All rights reserved. +// Copyright (C) 1998-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. +//-------------------------------------------------------------------------- +// sf_cidr.cc author Michael Altizer + +#include "sf_cidr.h" + +SfIpRet SfCidr::set(const char* src) +{ + return addr.set(src, &bits); +} + +/* Check if ip is contained within the network specified by this addr */ +/* Returns SFIP_EQUAL if so. + * XXX assumes that "ip" is not less specific than "addr" XXX +*/ +SfIpRet SfCidr::contains(const SfIp* ip) const +{ + unsigned int mask, temp, i; + const uint32_t* pn, * pi; + + /* SFIP_CONTAINS is returned here due to how sfvar_ip_in + * handles zero'ed IPs" */ + if (!ip) + return SFIP_CONTAINS; + + pn = addr.get_ip6_ptr(); + pi = ip->get_ip6_ptr(); + + /* Iterate over each 32 bit segment */ + for (i = 0; i < bits / 32; i++, pn++, pi++) + { + if (*pn != *pi) + return SFIP_NOT_CONTAINS; + } + + mask = 32 - (bits - 32 * i); + if (mask == 32) + return SFIP_CONTAINS; + + /* At this point, there are some number of remaining bits to check. + * Mask the bits we don't care about off of "ip" so we can compare + * the ints directly */ + temp = ntohl(*pi); + temp = (temp >> mask) << mask; + + /* If pn was setup correctly through this library, there is no need to + * mask off any bits of its own. */ + if (ntohl(*pn) == temp) + return SFIP_CONTAINS; + + return SFIP_NOT_CONTAINS; +} + diff --git a/src/sfip/sf_cidr.h b/src/sfip/sf_cidr.h new file mode 100644 index 000000000..f95335cd5 --- /dev/null +++ b/src/sfip/sf_cidr.h @@ -0,0 +1,166 @@ +//-------------------------------------------------------------------------- +// Copyright (C) 2014-2016 Cisco and/or its affiliates. All rights reserved. +// Copyright (C) 1998-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. +//-------------------------------------------------------------------------- +// sf_cidr.h author Michael Altizer + +#ifndef SF_CIDR_H +#define SF_CIDR_H + +#include "sfip/sf_ip.h" + +/* + * NOTE: As much as I'd love to make this a subclass of SfIp, member layout + * is undefined for POD inheritance. + */ + +struct SO_PUBLIC SfCidr +{ + /* + * Modifiers (incl. convenience ones that delegate to addr) + */ + void clear(); + void set(const SfCidr& src); + void set(const SfIp& src); + SfIpRet set(const void* src, int fam); + SfIpRet set(const char* src); + void set_bits(uint16_t new_bits); + + /* + * Accessors (incl. convenience ones that delegate to addr) + */ + const SfIp* get_addr() const; + uint16_t get_family() const; + uint16_t get_bits() const; + bool is_set() const; + + /* + * Containment checks + */ + bool fast_cont4(const SfIp& ip) const; + bool fast_cont6(const SfIp& ip) const; + SfIpRet contains(const SfIp* ip) const; + + const char* ntoa() const; + +private: + SfIp addr; + uint16_t bits; +} __attribute__((__packed__)); + + +inline void SfCidr::clear() +{ + addr.clear(); + bits = 0; +} + +inline void SfCidr::set(const SfCidr& src) +{ + addr.set(src.addr); + bits = src.bits; +} + +inline void SfCidr::set(const SfIp& src) +{ + addr.set(src); + bits = 128; +} + +inline SfIpRet SfCidr::set(const void* src, int fam) +{ + SfIpRet ret = addr.set(src, fam); + if (ret != SFIP_SUCCESS) + return ret; + bits = 128; + return SFIP_SUCCESS; +} + +inline void SfCidr::set_bits(uint16_t new_bits) +{ + if (new_bits > 128) + return; + bits = new_bits; +} + +inline const SfIp* SfCidr::get_addr() const +{ + return &addr; +} + +inline uint16_t SfCidr::get_family() const +{ + return addr.get_family(); +} + +inline uint16_t SfCidr::get_bits() const +{ + return bits; +} + +inline bool SfCidr::is_set() const +{ + return (addr.is_set() || + ((addr.get_family() == AF_INET || addr.get_family() == AF_INET6) && + bits != 128)); +} + +inline bool SfCidr::fast_cont4(const SfIp& ip) const +{ + uint32_t shift = 128 - bits; + uint32_t needle = ntohl(ip.get_ip4_value()); + uint32_t haystack = ntohl(addr.get_ip4_value()); + + if (haystack == 0) + return true; + + needle >>= shift; + needle <<= shift; + + return haystack == needle; +} + +inline bool SfCidr::fast_cont6(const SfIp& ip) const +{ + uint32_t needle; + int words = bits / 32; + int shift, i; + + for (i = 0; i < words; i++) + { + if (addr.get_ip6_ptr()[i] != ip.get_ip6_ptr()[i]) + return false; + } + + shift = 32 - (bits % 32); + if (shift == 32) + return true; + + needle = ntohl(ip.get_ip6_ptr()[i]); + + needle >>= shift; + needle <<= shift; + + return ntohl(addr.get_ip6_ptr()[i]) == needle; +} + +inline const char* SfCidr::ntoa() const +{ + return addr.ntoa(); +} + +#endif diff --git a/src/sfip/sf_ip.cc b/src/sfip/sf_ip.cc index 1e2f759d8..6a27b11fc 100644 --- a/src/sfip/sf_ip.cc +++ b/src/sfip/sf_ip.cc @@ -16,14 +16,10 @@ // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- +// sf_ip.cc author Michael Altizer +// based on work by Adam Keeton -/* - * Adam Keeton - * sf_ip.c - * 11/17/06 - * - * Library for managing IP addresses of either v6 or v4 families. -*/ +/* Library for managing IP addresses of either v6 or v4 families. */ #include "sf_ip.h" @@ -31,32 +27,13 @@ #include "config.h" #endif -#include -#include -#include -#include -#include /* For ceil */ - -/* For inet_pton */ -#include -#include +#include // For ceil #include "main/thread.h" -#include "protocols/ipv6.h" #include "utils/util.h" +#include "utils/util_net.h" -#if 0 -/* Support function .. but could see some external uses */ -static inline int sfip_length(sfip_t* ip) -{ - ARG_CHECK1(ip, 0); - - if (sfip_family(ip) == AF_INET) - return 4; - return 16; -} - -#endif +#include "sf_cidr.h" /* Support function */ // note that an ip6 address may have a trailing dotted quad form @@ -67,7 +44,7 @@ static inline int sfip_length(sfip_t* ip) static inline int sfip_str_to_fam(const char* str) { const char* s; - ARG_CHECK1(str, 0); + assert(str); s = strchr(str, (int)':'); if ( s && strchr(s+1, (int)':') ) return AF_INET6; @@ -76,42 +53,38 @@ static inline int sfip_str_to_fam(const char* str) return AF_UNSPEC; } -/* Place-holder allocation incase we want to do something more indepth later */ -static inline sfip_t* _sfip_alloc() -{ - return (sfip_t*)snort_calloc(sizeof(sfip_t)); -} - /* Masks off 'val' bits from the IP contained within 'ip' */ -static inline int sfip_cidr_mask(sfip_t* ip, int val) +inline int SfIp::cidr_mask(int val) { - int i; - unsigned int mask = 0; - unsigned int* p; - int index = (int)ceil(val / 32.0) - 1; + uint32_t* p; + int index, bits; - ARG_CHECK1(ip, SFIP_ARG_ERR); + p = ip32; - p = ip->ip32; - - if ( val < 0 || - ((sfip_family(ip) == AF_INET6) && val > 128) || - ((sfip_family(ip) == AF_INET) && val > 32) ) - { + if (val < 0 || val > 128) return SFIP_ARG_ERR; - } + + if (val == 128) + return SFIP_SUCCESS; /* Build the netmask by converting "val" into * the corresponding number of bits that are set */ - for (i = 0; i < 32- (val - (index * 32)); i++) - mask = (mask<<1) + 1; + index = (int) ceil(val / 32.0) - 1; + bits = 32 - (val - (index * 32)); + if (bits) + { + unsigned int mask; - p[index] = htonl((ntohl(p[index]) & ~mask)); + mask = ~0; + mask >>= bits; + mask <<= bits; + p[index] &= htonl(mask); + } index++; /* 0 off the rest of the IP */ - for (; index<4; index++) + for (; index < 4; index++) p[index] = 0; return SFIP_SUCCESS; @@ -120,103 +93,46 @@ static inline int sfip_cidr_mask(sfip_t* ip, int val) /* Converts string IP format to an array of values. Also checks IP address format. Specifically look for issues that inet_pton either overlooks or is inconsistent about. */ -SFIP_RET sfip_convert_ip_text_to_binary(const int family, const char* ip, void* dst) +SfIpRet SfIp::pton(const int fam, const char* ip) { const char* my_ip = ip; + void* dst; - if ( my_ip == NULL ) - return( SFIP_FAILURE ); + if (!my_ip) + return SFIP_FAILURE; /* Across platforms, inet_pton() is inconsistent about leading 0's in - AF_INET (ie IPv4 addresses. */ - if ( family == AF_INET ) + AF_INET (ie IPv4 addresses). */ + if (fam == AF_INET) { char chr; bool new_octet; new_octet = true; - while ( (chr = *my_ip++) != '\0') + while ((chr = *my_ip++) != '\0') { /* If we are at the first char of a new octet, look for a leading zero followed by another digit */ - if ( new_octet && (chr == '0') && isdigit(*my_ip)) - return( SFIP_INET_PARSE_ERR ); + if (new_octet && (chr == '0') && isdigit(*my_ip)) + return SFIP_INET_PARSE_ERR; /* when we see an octet separator, set the flag to start looking for a leading zero. */ new_octet = (chr == '.'); } + ip32[0] = ip32[1] = ip16[4] = 0; + ip16[5] = 0xffff; + dst = &ip32[3]; } + else + dst = ip32; - if ( inet_pton(family, ip, dst) < 1 ) - return( SFIP_INET_PARSE_ERR ); - - return( SFIP_SUCCESS ); /* Otherwise, ip is OK */ -} - -/* Allocate IP address from a character array describing the IP */ -sfip_t* sfip_alloc(const char* ip, SFIP_RET* status) -{ - SFIP_RET tmp; - sfip_t* ret; - - if (!ip) - { - if (status) - *status = SFIP_ARG_ERR; - return NULL; - } - - if ((ret = _sfip_alloc()) == NULL) - { - if (status) - *status = SFIP_ALLOC_ERR; - return NULL; - } - - if ( (tmp = sfip_pton(ip, ret)) != SFIP_SUCCESS) - { - if (status) - *status = tmp; - - sfip_free(ret); - return NULL; - } - - if (status) - *status = SFIP_SUCCESS; - - return ret; -} - -/* Allocate IP address from an array of 8 byte integers */ -sfip_t* sfip_alloc_raw(void* ip, int family, SFIP_RET* status) -{ - sfip_t* ret; - - if (!ip) - { - if (status) - *status = SFIP_ARG_ERR; - return NULL; - } - - if ((ret = _sfip_alloc()) == NULL) - { - if (status) - *status = SFIP_ALLOC_ERR; - return NULL; - } - - ret->bits = (family==AF_INET ? 32 : 128); - ret->family = family; - /* XXX Replace with appropriate "high speed" copy */ - memcpy(ret->ip8, ip, ret->bits/8); + if (inet_pton(fam, ip, dst) < 1) + return SFIP_INET_PARSE_ERR; - if (status) - *status = SFIP_SUCCESS; + family = fam; - return ret; + return SFIP_SUCCESS; /* Otherwise, ip is OK */ } /* Support function for _netmask_str_to_bit_count */ @@ -288,19 +204,19 @@ static inline int _netmask_str_to_bit_count(char* mask, int family) } /* Parses "src" and stores results in "dst" */ -SFIP_RET sfip_pton(const char* src, sfip_t* dst) +SfIpRet SfIp::set(const char* src, uint16_t* srcBits) { char* mask; char* sfip_buf; char* ip; int bits; - if (!dst || !src) + if (!src) return SFIP_ARG_ERR; sfip_buf = snort_strdup(src); ip = sfip_buf; - dst->family = sfip_str_to_fam(src); + family = sfip_str_to_fam(src); /* skip whitespace or opening bracket */ while (isspace((int)*ip) || (*ip == '[')) @@ -320,8 +236,8 @@ SFIP_RET sfip_pton(const char* src, sfip_t* dst) mask++; /* verify a leading digit */ - if (((dst->family == AF_INET6) && !isxdigit((int)*mask)) || - ((dst->family == AF_INET) && !isdigit((int)*mask))) + if (((family == AF_INET6) && !isxdigit((int)*mask)) || + ((family == AF_INET) && !isdigit((int)*mask))) { snort_free(sfip_buf); return SFIP_CIDR_ERR; @@ -335,7 +251,7 @@ SFIP_RET sfip_pton(const char* src, sfip_t* dst) } else if ( /* If this is IPv4, ia ':' may used specified to indicate a netmask */ - ((dst->family == AF_INET) && (mask = strchr(ip, (int)':')) != NULL) || + ((family == AF_INET) && (mask = strchr(ip, (int)':')) != NULL) || /* We've already skipped the leading whitespace, if there is more * whitespace, then there's probably a netmask specified after it. */ @@ -353,15 +269,15 @@ SFIP_RET sfip_pton(const char* src, sfip_t* dst) /* Make sure we're either looking at a valid digit, or a leading * colon, such as can be the case with IPv6 */ - if (((dst->family == AF_INET) && isdigit((int)*mask)) || - ((dst->family == AF_INET6) && (isxdigit((int)*mask) || *mask == ':'))) + if (((family == AF_INET) && isdigit((int)*mask)) || + ((family == AF_INET6) && (isxdigit((int)*mask) || *mask == ':'))) { bits = _netmask_str_to_bit_count(mask, sfip_str_to_fam(mask)); } /* No netmask */ else { - if (dst->family == AF_INET) + if (family == AF_INET) bits = 32; else bits = 128; @@ -370,179 +286,111 @@ SFIP_RET sfip_pton(const char* src, sfip_t* dst) /* No netmask */ else { - if (dst->family == AF_INET) + if (family == AF_INET) bits = 32; else bits = 128; } - if (sfip_convert_ip_text_to_binary(dst->family, ip, dst->ip8) != SFIP_SUCCESS) + if (pton(family, ip) != SFIP_SUCCESS) { snort_free(sfip_buf); return SFIP_INET_PARSE_ERR; } /* Store mask */ - dst->bits = bits; + bits += (family == AF_INET && bits >= 0) ? 96 : 0; /* Apply mask */ - if (sfip_cidr_mask(dst, bits) != SFIP_SUCCESS) + if (cidr_mask(bits) != SFIP_SUCCESS) { snort_free(sfip_buf); return SFIP_INVALID_MASK; } + if (srcBits) + *srcBits = bits; + else if (bits != 128) + { + snort_free(sfip_buf); + return SFIP_INET_PARSE_ERR; + } + snort_free(sfip_buf); return SFIP_SUCCESS; } -/* Sets existing IP, "dst", to be source IP, "src" */ -SFIP_RET sfip_set_raw(sfip_t* dst, const void* src, int family) +SfIpRet SfIp::set(const void* src, int fam) { - ARG_CHECK3(dst, src, dst->ip32, SFIP_ARG_ERR); - - dst->family = family; + assert(src); + family = fam; if (family == AF_INET) { - dst->ip32[0] = *(uint32_t*)src; - memset(&dst->ip32[1], 0, 12); - dst->bits = 32; + ip32[0] = ip32[1] = ip16[4] = 0; + ip16[5] = 0xffff; + ip32[3] = *(uint32_t*)src; } else if (family == AF_INET6) - { - memcpy(dst->ip8, src, 16); - dst->bits = 128; - } + memcpy(ip8, src, 16); else - { return SFIP_ARG_ERR; - } return SFIP_SUCCESS; } -/* Sets existing IP, "dst", to be source IP, "src" */ -SFIP_RET sfip_set_ip(sfip_t* dst, const sfip_t* src) +/* Obfuscates this IP with an obfuscation CIDR + Makes this: ob | (this & mask) */ +void SfIp::obfuscate(SfCidr* ob) { - ARG_CHECK2(dst, src, SFIP_ARG_ERR); - - dst->family = src->family; - dst->bits = src->bits; - dst->ip32[0] = src->ip32[0]; - dst->ip32[1] = src->ip32[1]; - dst->ip32[2] = src->ip32[2]; - dst->ip32[3] = src->ip32[3]; - - return SFIP_SUCCESS; -} - -/* Obfuscates an IP - * Makes 'ip': ob | (ip & mask) */ -void sfip_obfuscate(sfip_t* ob, sfip_t* ip) -{ - unsigned int* ob_p, * ip_p; + const uint32_t* ob_p; int index, i; unsigned int mask = 0; - if (!ob || !ip) + if (!ob) return; - ob_p = ob->ip32; - ip_p = ip->ip32; + ob_p = ob->get_addr()->get_ip6_ptr(); /* Build the netmask by converting "val" into * the corresponding number of bits that are set */ - index = (int)ceil(ob->bits / 32.0) - 1; + index = (int)ceil(ob->get_bits() / 32.0) - 1; - for (i = 0; i < 32- (ob->bits - (index * 32)); i++) - mask = (mask<<1) + 1; + for (i = 0; i < 32 - (ob->get_bits() - (index * 32)); i++) + mask = (mask << 1) + 1; /* Note: The old-Snort obfuscation code uses !mask for masking. * hence, this code uses the same algorithm as sfip_cidr_mask * except the mask below is not negated. */ - ip_p[index] = htonl((ntohl(ip_p[index]) & mask)); + ip32[index] = htonl((ntohl(ip32[index]) & mask)); /* 0 off the start of the IP */ while ( index > 0 ) - ip_p[--index] = 0; + ip32[--index] = 0; /* OR remaining pieces */ - ip_p[0] |= ob_p[0]; - ip_p[1] |= ob_p[1]; - ip_p[2] |= ob_p[2]; - ip_p[3] |= ob_p[3]; + ip32[0] |= ob_p[0]; + ip32[1] |= ob_p[1]; + ip32[2] |= ob_p[2]; + ip32[3] |= ob_p[3]; } -/* Check if ip is contained within the network specified by net */ -/* Returns SFIP_EQUAL if so. - * XXX sfip_contains assumes that "ip" is - * not less-specific than "net" XXX -*/ -SFIP_RET sfip_contains(const sfip_t* net, const sfip_t* ip) +void SfIp::ntop(char* buf, int bufsize) const { - unsigned int bits, mask, temp, i; - int net_fam, ip_fam; - const unsigned int* p1, * p2; - - /* SFIP_CONTAINS is returned here due to how sfvar_ip_in - * handles zero'ed IPs" */ - ARG_CHECK2(net, ip, SFIP_CONTAINS); - - bits = sfip_bits(net); - net_fam = sfip_family(net); - ip_fam = sfip_family(ip); - - /* If the families are mismatched, check if we're really comparing - * an IPv4 with a mapped IPv4 (in IPv6) address. */ - if (net_fam != ip_fam) - { - if ((net_fam != AF_INET) || !sfip_ismapped(ip)) - return SFIP_ARG_ERR; - - /* Both are really IPv4. Only compare last 4 bytes of 'ip'*/ - p1 = net->ip32; - p2 = &ip->ip32[3]; - - /* Mask off bits */ - bits = 32 - bits; - temp = (ntohl(*p2) >> bits) << bits; - - if (ntohl(*p1) == temp) - return SFIP_CONTAINS; - - return SFIP_NOT_CONTAINS; - } - - p1 = net->ip32; - p2 = ip->ip32; - - /* Iterate over each 32 bit segment */ - for (i=0; i < bits/32 && i < 3; i++, p1++, p2++) - { - if (*p1 != *p2) - return SFIP_NOT_CONTAINS; - } - - mask = 32 - (bits - 32*i); - if ( mask == 32 ) - return SFIP_CONTAINS; + snort_inet_ntop(family, get_ptr(), buf, bufsize); +} - /* At this point, there are some number of remaining bits to check. - * Mask the bits we don't care about off of "ip" so we can compare - * the ints directly */ - temp = ntohl(*p2); - temp = (temp >> mask) << mask; +/* Uses a static buffer to return a string representation of the IP */ +const char* SfIp::ntoa() const +{ + static THREAD_LOCAL char buf[INET6_ADDRSTRLEN]; - /* If p1 was setup correctly through this library, there is no need to - * mask off any bits of its own. */ - if (ntohl(*p1) == temp) - return SFIP_CONTAINS; + ntop(buf, sizeof(buf)); - return SFIP_NOT_CONTAINS; + return buf; } -void sfip_raw_ntop(int family, const void* ip_raw, char* buf, int bufsize) +void snort_inet_ntop(int family, const void* ip_raw, char* buf, int bufsize) { if (!ip_raw || !buf || (family != AF_INET && family != AF_INET6) || @@ -580,18 +428,6 @@ void sfip_raw_ntop(int family, const void* ip_raw, char* buf, int bufsize) i++; } - - /* Check if this is really just an IPv4 address represented as 6, - * in compatible format */ -#if 0 - } - else if (!field[0] && !field[1] && !field[2]) - { - unsigned char* p = (unsigned char*)(&ip->ip[12]); - - for (i=0; p < &ip->ip[16]; p++) - i += sprintf(&buf[i], "%d.", *p); -#endif } else { @@ -613,7 +449,7 @@ void sfip_raw_ntop(int family, const void* ip_raw, char* buf, int bufsize) #endif } -void sfip_ntop(const sfip_t* ip, char* buf, int bufsize) +void sfip_ntop(const SfIp* ip, char* buf, int bufsize) { if (!ip) { @@ -621,40 +457,14 @@ void sfip_ntop(const sfip_t* ip, char* buf, int bufsize) buf[0] = 0; return; } - - sfip_raw_ntop(sfip_family(ip), ip->ip32, buf, bufsize); + ip->ntop(buf, bufsize); } -/* Uses a static buffer to return a string representation of the IP */ -char* sfip_to_str(const sfip_t* ip) +bool SfIp::is_mapped() const { - static THREAD_LOCAL char buf[INET6_ADDRSTRLEN]; - - sfip_ntop(ip, buf, sizeof(buf)); - - return buf; -} - -void sfip_free(sfip_t* ip) -{ - if (ip) - snort_free(ip); -} - -int sfip_ismapped(const sfip_t* ip) -{ - const unsigned int* p; - - ARG_CHECK1(ip, 0); - - if (sfip_family(ip) == AF_INET) - return 0; - - p = ip->ip32; - - if (p[0] || p[1] || (ntohl(p[2]) != 0xffff && p[2] != 0)) - return 0; + if (ip32[0] || ip32[1] || ip16[4] || (ip16[5] != 0xffff && ip16[5])) + return false; - return 1; + return true; } diff --git a/src/sfip/sf_ip.h b/src/sfip/sf_ip.h index 5afced821..f037f866f 100644 --- a/src/sfip/sf_ip.h +++ b/src/sfip/sf_ip.h @@ -16,205 +16,278 @@ // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- - -/* - * Adam Keeton - * sf_ip.h - * 11/17/06 -*/ +// sf_ip.h author Michael Altizer +// based on work by Adam Keeton #ifndef SF_IP_H #define SF_IP_H -// Provides many convenient functions to process IP. It is a small tool box for -// IP operations. - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include -#include #include - -#include "sfip/sfip_t.h" -#include "sfip/sf_returns.h" -#include "main/snort_debug.h" -#include "main/snort_types.h" +#include +#include +#include #include -/* define SFIP_ROBUST to check pointers passed into the sfip libs. - * Robustification should not be enabled if the client code is trustworthy. - * Namely, if pointers are checked once in the client, or are pointers to - * data allocated on the stack, there's no need to check them again here. - * The intention is to prevent the same stack-allocated variable from being - * checked a dozen different times. */ -#define SFIP_ROBUST - -#ifdef SFIP_ROBUST - -#define ARG_CHECK1(a, z) if (!a) return z; -#define ARG_CHECK2(a, b, z) if (!a || !b) return z; -#define ARG_CHECK3(a, b, c, z) if (!a || !b || !c) return z; - -#elif defined(DEBUG) - -#define ARG_CHECK1(a, z) assert(a); -#define ARG_CHECK2(a, b, z) assert(a); assert(b); -#define ARG_CHECK3(a, b, c, z) assert(a); assert(b); assert(c); - -#else - -#define ARG_CHECK1(a, z) -#define ARG_CHECK2(a, b, z) -#define ARG_CHECK3(a, b, c, z) - -#endif - -/* IP allocations and setting ******************************************/ - -/* Converts string IP format to an array of values. Also checks IP address format. */ -SO_PUBLIC SFIP_RET sfip_convert_ip_text_to_binary(const int family, const char* ip, void* dst); - -/* Parses "src" and stores results in "dst" - If the conversion is invalid, returns SFIP_FAILURE */ -SO_PUBLIC SFIP_RET sfip_pton(const char* src, sfip_t* dst); - -/* Allocate IP address from a character array describing the IP */ -SO_PUBLIC sfip_t* sfip_alloc(const char* ip, SFIP_RET* status); - -/* Frees an sfip_t */ -SO_PUBLIC void sfip_free(sfip_t* ip); +#include "main/snort_types.h" +#include "sfip/sf_returns.h" -/* Allocate IP address from an array of integers. The array better be - * long enough for the given family! */ -SO_PUBLIC sfip_t* sfip_alloc_raw(void* ip, int family, SFIP_RET* status); +struct SfCidr; -/* Sets existing IP, "dst", to a raw source IP (4 or 16 bytes, - * according to family) */ -SO_PUBLIC SFIP_RET sfip_set_raw(sfip_t* dst, const void* src, int src_family); +struct SO_PUBLIC SfIp +{ + /* + * Modifiers + */ + void clear(); + void set(const SfIp& src); + SfIpRet set(const char* src, uint16_t* srcBits = nullptr); + /* Sets to a raw source IP (4 or 16 bytes, according to family) */ + SfIpRet set(const void* src, int fam); + /* Converts string IP format to an array of values. Also checks IP address format. */ + SfIpRet pton(const int fam, const char* ip); + + /* + * Accessors + */ + uint16_t get_family() const; + uint32_t get_ip4_value() const; + const uint32_t* get_ip4_ptr() const; + const uint32_t* get_ip6_ptr() const; + const uint32_t* get_ptr() const; + bool is_set() const; + bool is_ip6() const; + bool is_ip4() const; + + /* + * Comparison functions + */ + bool equals(const SfIp& rhs, bool match_unset = true) const; + bool less_than(const SfIp& rhs) const; + bool greater_than(const SfIp& rhs) const; + SfIpRet compare(const SfIp& ip2, bool match_unset = true) const; + bool fast_eq4(const SfIp& ip2) const; + bool fast_lt6(const SfIp& ip2) const; + bool fast_gt6(const SfIp& ip2) const; + bool fast_eq6(const SfIp& ip2) const; + bool fast_equals_raw(const SfIp& ip2) const; + + /* + * Miscellaneous + */ + /* Returns true if the IPv6 address appears mapped. */ + bool is_mapped() const; + bool is_loopback() const; + bool is_private() const; + + void ntop(char* buf, int bufsize) const; + const char* ntoa() const; + + void obfuscate(SfCidr* ob); + +private: + int cidr_mask(int val); + bool _is_equals(const SfIp& rhs) const; + bool _is_lesser(const SfIp& rhs) const; + SfIpRet _ip6_cmp(const SfIp& ip2) const; + + union + { + uint8_t ip8[16]; + uint16_t ip16[8]; + uint32_t ip32[4]; + }; + int16_t family; +} __attribute__((__packed__)); -/* Sets existing IP, "dst", to be source IP, "src" */ -SO_PUBLIC SFIP_RET sfip_set_ip(sfip_t* dst, const sfip_t* src); -/* Obfuscates an IP */ -void sfip_obfuscate(sfip_t* ob, sfip_t* ip); +/* + * Member function definitions + */ -/* return required size (eg for hashing) - * requires that address bytes be the last field in sfip_t */ -inline unsigned int sfip_size(const sfip_t* ipt) +inline void SfIp::clear() { - if ( ipt->family == AF_INET6 ) - return sizeof(*ipt); - return (unsigned int)((ipt->ip8+4) - (uint8_t*)ipt); + family = 0; + ip32[0] = ip32[1] = ip32[2] = ip32[3] = 0; } -/* Member-access *******************************************************/ +inline void SfIp::set(const SfIp& src) +{ + /* This is a simple structure, so is this really better than + *this = src?. */ + family = src.family; + ip32[0] = src.ip32[0]; + ip32[1] = src.ip32[1]; + ip32[2] = src.ip32[2]; + ip32[3] = src.ip32[3]; +} -/* Returns the family of "ip", either AF_INET or AF_INET6 */ -/* XXX This is a performance critical function, -* need to determine if it's safe to not check these pointers */ -// ARG_CHECK1(ip, 0); -#define sfip_family(ip) ip->family +inline uint16_t SfIp::get_family() const +{ + return family; +} -/* Returns the number of bits used for masking "ip" */ -inline unsigned char sfip_bits(const sfip_t* ip) +inline uint32_t SfIp::get_ip4_value() const { - ARG_CHECK1(ip, 0); - return (unsigned char)ip->bits; + return ip32[3]; } -inline void sfip_set_bits(sfip_t* p, int bits) +inline const uint32_t* SfIp::get_ip4_ptr() const { - if (!p) - return; + return &ip32[3]; +} - if (bits < 0 || bits > 128) - return; +inline const uint32_t* SfIp::get_ip6_ptr() const +{ + return ip32; +} - p->bits = (int16_t)bits; +inline const uint32_t* SfIp::get_ptr() const +{ + if (is_ip4()) + return &ip32[3]; + return ip32; } -/* Returns the raw IP address as an in6_addr */ -//inline struct in6_addr sfip_to_raw(sfip_t *); - -/* IP Comparisons ******************************************************/ - -// Functions which will be defined below. -inline int sfip_is_set(const sfip_t& ip); -inline int sfip_is_set(const sfip_t* const ip); -inline bool sfip_equals(const sfip_t* const lhs, const sfip_t* const rhs); -inline bool sfip_unset_equals(const sfip_t* const lhs, const sfip_t* const rhs); -inline bool sfip_not_equals(const sfip_t* const lhs, const sfip_t* const rhs); -inline bool sfip_lesser(const sfip_t* const lhs, const sfip_t* const rhs); -inline bool sfip_greater(const sfip_t* const lhs, const sfip_t* const rhs); -inline void sfip_clear(sfip_t& x); -inline void sfip_copy(sfip_t& lhs, const sfip_t* const rhs); - -/* Check if ip is contained within the network specified by net - Returns SFIP_EQUAL if so */ -SO_PUBLIC SFIP_RET sfip_contains(const sfip_t* net, const sfip_t* ip); - -#if 0 -/* Returns 1 if the IP is non-zero. 0 otherwise */ -/* XXX This is a performance critical function, \ - * need to determine if it's safe to not check these pointers */ -inline int sfip_is_set(const sfip_t* ip) +inline bool SfIp::is_set() const { -// ARG_CHECK1(ip, -1); - return ip->ip32[0] || - ( (ip->family == AF_INET6) && - (ip->ip32[1] || - ip->ip32[2] || - ip->ip32[3] || ip->bits != 128)) || ((ip->family == AF_INET) && ip->bits != 32); + return ((family == AF_INET && ip32[3]) || + (family == AF_INET6 && + (ip32[0] || ip32[1] || ip32[3] || ip16[4] || + (ip16[5] && ip16[5] != 0xffff)))); } -#endif +inline bool SfIp::is_ip6() const +{ + return family == AF_INET6; +} -/* Return 1 if the IP is a loopback IP */ +inline bool SfIp::is_ip4() const +{ + return family == AF_INET; +} -/* Returns 1 if the IP is non-zero. 0 otherwise */ -inline int sfip_is_loopback(const sfip_t* ip) +inline bool SfIp::is_loopback() const { - const unsigned int* p; + /* Check the first 80 bits in an IPv6 address, and + verify they're zero. If not, it's not a loopback */ + if (ip32[0] || ip32[1] || ip16[4]) + return false; - ARG_CHECK1(ip, 0); + if (ip16[5] == 0xffff) + { + /* ::ffff:127.0.0.0/104 is IPv4 loopback mapped over IPv6 */ + return (ip8[12] == 0x7f); + } - if (sfip_family(ip) == AF_INET) + if (!ip16[5]) { - // 127.0.0.0/8 is IPv4 loopback - return (ip->ip8[0] == 0x7f); + /* ::7f00:0/104 is ipv4 compatible ipv6 + ::1 is the IPv6 loopback */ + return (ip32[3] == htonl(0x1) || ip8[12] == 0x7f); } - p = ip->ip32; + return false; +} - /* Check the first 64 bits in an IPv6 address, and - verify they're zero. If not, it's not a loopback */ - if (p[0] || p[1]) - return 0; +inline bool SfIp::is_private() const +{ + /* Check the first 80 bits in an IPv6 address, and + verify they're zero. If not, it's not a loopback. */ + if (ip32[0] || ip32[1] || ip16[4]) + return false; + + /* (Mapped) v4 private addresses */ + if (ip16[5] == 0xffff) + { + /* + * 10.0.0.0 - 10.255.255.255 (10/8 prefix) + * 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) + * 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) + */ + return ( (ip8[12] == 10) + || ((ip8[12] == 172) && ((ip8[13] & 0xf0) == 16)) + || ((ip8[12] == 192) && (ip8[13] == 168)) ); + } /* Check if the 3rd 32-bit int is zero */ - if ( p[2] == 0 ) + if (!ip16[5]) { - /* ::7f00:0/104 is ipv4 compatible ipv6 + /* ::ipv4 compatible ipv6 ::1 is the IPv6 loopback */ - return ( (ip->ip8[12] == 0x7f) || (ntohl(p[3]) == 0x1) ); + return ( (ip8[12] == 10) + || ((ip8[12] == 172) && ((ip8[13] & 0xf0) == 16)) + || ((ip8[12] == 192) && (ip8[13] == 168)) + || (ip32[3] == htonl(0x1)) ); } - /* Check the 3rd 32-bit int for a mapped IPv4 address */ - if ( ntohl(p[2]) == 0xffff ) + + return false; +} + +inline bool SfIp::_is_equals(const SfIp& rhs) const +{ + if (is_ip4()) { - /* ::ffff:127.0.0.0/104 is IPv4 loopback mapped over IPv6 */ - return ( ip->ip8[12] == 0x7f ); + return (rhs.is_ip4()) && + (ip32[3] == rhs.ip32[3]); + } + else if (is_ip6()) + { + return (rhs.is_ip6()) && + (ip32[0] == rhs.ip32[0]) && + (ip32[1] == rhs.ip32[1]) && + (ip32[2] == rhs.ip32[2]) && + (ip32[3] == rhs.ip32[3]); + } + return false; +} + +inline bool SfIp::_is_lesser(const SfIp& rhs) const +{ + if (is_ip4()) + { + return (rhs.is_ip4() && + (htonl(ip32[3]) < htonl(rhs.ip32[3]))); } - return 0; + else if (is_ip6()) + { + return (rhs.is_ip6() && + (htonl(ip32[0]) < htonl(rhs.ip32[0])) && + (htonl(ip32[1]) < htonl(rhs.ip32[1])) && + (htonl(ip32[2]) < htonl(rhs.ip32[2])) && + (htonl(ip32[3]) < htonl(rhs.ip32[3]))); + } + return false; } -/* Returns 1 if the IPv6 address appears mapped. 0 otherwise. */ -int sfip_ismapped(const sfip_t* ip); +inline bool SfIp::equals(const SfIp& rhs, bool match_unset) const +{ + if (!is_set() || !rhs.is_set()) + return match_unset; + + return _is_equals(rhs); +} -/* Support function for sfip_compare */ -inline SFIP_RET _ip4_cmp(uint32_t ip1, uint32_t ip2) +inline bool SfIp::less_than(const SfIp& rhs) const +{ + // I'm copying and pasting. Don't ask me why this is different then sfip_equals + if (!is_set() || !rhs.is_set()) + return false; + + return _is_lesser(rhs); +} + +inline bool SfIp::greater_than(const SfIp& rhs) const +{ + // I'm copying and pasting. Don't ask me why this is different then sfip_equals + if (!is_set() || !rhs.is_set()) + return false; + + return rhs._is_lesser(*this); +} + +/* Support function for SfIp::compare() */ +inline SfIpRet _ip4_cmp(uint32_t ip1, uint32_t ip2) { uint32_t hip1 = htonl(ip1); uint32_t hip2 = htonl(ip2); @@ -225,20 +298,14 @@ inline SFIP_RET _ip4_cmp(uint32_t ip1, uint32_t ip2) return SFIP_EQUAL; } -/* Support function for sfip_compare */ -inline SFIP_RET _ip6_cmp(const sfip_t* ip1, const sfip_t* ip2) +/* Support function for SfIp::compare() */ +inline SfIpRet SfIp::_ip6_cmp(const SfIp& ip2) const { - SFIP_RET ret; + SfIpRet ret; const uint32_t* p1, * p2; - /* XXX - * Argument are assumed trusted! - * This function is presently only called by sfip_compare - * on validated pointers. - * XXX */ - - p1 = ip1->ip32; - p2 = ip2->ip32; + p1 = ip32; + p2 = ip2.ip32; if ( (ret = _ip4_cmp(p1[0], p2[0])) != SFIP_EQUAL) return ret; @@ -252,460 +319,143 @@ inline SFIP_RET _ip6_cmp(const sfip_t* ip1, const sfip_t* ip2) return ret; } -/* Compares two IPs - * Returns SFIP_LESSER, SFIP_EQUAL, SFIP_GREATER, if ip1 is less than, equal to, - * or greater than ip2 In the case of mismatched families, the IPv4 address - * is converted to an IPv6 representation. */ -/* XXX-IPv6 Should add version of sfip_compare that just tests equality */ -inline SFIP_RET sfip_compare(const sfip_t* const ip1, const sfip_t* const ip2) +/* + * Returns SFIP_LESSER, SFIP_EQUAL, SFIP_GREATER, if this is less than, equal to, + * or greater than ip2. In the case of mismatched families, the IPv4 address + * is converted to an IPv6 representation. + * To support existing Snort code, an unset IP is considered to match anything + * unless 'match_unset' is set to false. + */ +inline SfIpRet SfIp::compare(const SfIp& ip2, bool match_unset) const { - int f1,f2; - - ARG_CHECK2(ip1, ip2, SFIP_ARG_ERR); - - /* This is being done because at some points in the existing Snort code, - * an unset IP is considered to match anything. Thus, if either IP is not - * set here, it's considered equal. */ - if (!sfip_is_set(ip1) || !sfip_is_set(ip2)) - return SFIP_EQUAL; - - f1 = sfip_family(ip1); - f2 = sfip_family(ip2); - - if (f1 == AF_INET && f2 == AF_INET) - { - return _ip4_cmp(*ip1->ip32, *ip2->ip32); - } -/* Mixed families not presently supported */ -#if 0 - else if (f1 == AF_INET && f2 == AF_INET6) - { - conv = sfip_4to6(ip1); - return _ip6_cmp(&conv, ip2); - } - else if (f1 == AF_INET6 && f2 == AF_INET) - { - conv = sfip_4to6(ip2); - return _ip6_cmp(ip1, &conv); - } - else + if (!is_set() || !ip2.is_set()) { - return _ip6_cmp(ip1, ip2); - } -#endif - else if (f1 == AF_INET6 && f2 == AF_INET6) - { - return _ip6_cmp(ip1, ip2); - } - - return SFIP_FAILURE; -} - -/* Compares two IPs - * Returns SFIP_LESSER, SFIP_EQUAL, SFIP_GREATER, if ip1 is less than, equal to, - * or greater than ip2 In the case of mismatched families, the IPv4 address - * is converted to an IPv6 representation. */ -/* XXX-IPv6 Should add version of sfip_compare that just tests equality */ -inline SFIP_RET sfip_compare_unset(const sfip_t* const ip1, const sfip_t* const ip2) -{ - int f1,f2; - - ARG_CHECK2(ip1, ip2, SFIP_ARG_ERR); - - /* This is to handle the special case when one of the values being - * unset is considered to match nothing. This is the opposite of - * sfip_compare(), defined above. Thus, if either IP is not - * set here, it's considered not equal. */ - if (!sfip_is_set(ip1) || !sfip_is_set(ip2)) + if (match_unset) + return SFIP_EQUAL; return SFIP_FAILURE; - - f1 = sfip_family(ip1); - f2 = sfip_family(ip2); - - if (f1 == AF_INET && f2 == AF_INET) - { - return _ip4_cmp(*ip1->ip32, *ip2->ip32); - } -/* Mixed families not presently supported */ -#if 0 - else if (f1 == AF_INET && f2 == AF_INET6) - { - conv = sfip_4to6(ip1); - return _ip6_cmp(&conv, ip2); - } - else if (f1 == AF_INET6 && f2 == AF_INET) - { - conv = sfip_4to6(ip2); - return _ip6_cmp(ip1, &conv); - } - else - { - return _ip6_cmp(ip1, ip2); - } -#endif - else if (f1 == AF_INET6 && f2 == AF_INET6) - { - return _ip6_cmp(ip1, ip2); } - return SFIP_FAILURE; -} - -inline int sfip_fast_lt4(const sfip_t* const ip1, const sfip_t* const ip2) -{ - return *ip1->ip32 < *ip2->ip32; -} + if (is_ip4() && ip2.is_ip4()) + return _ip4_cmp(get_ip4_value(), ip2.get_ip4_value()); -inline int sfip_fast_gt4(const sfip_t* const ip1, const sfip_t* const ip2) -{ - return *ip1->ip32 > *ip2->ip32; + return _ip6_cmp(ip2); } -inline int sfip_fast_eq4(const sfip_t* const ip1, const sfip_t* const ip2) +inline bool SfIp::fast_eq4(const SfIp& ip2) const { - return *ip1->ip32 == *ip2->ip32; + return get_ip4_value() == ip2.get_ip4_value(); } -inline int sfip_fast_lt6(const sfip_t* const ip1, const sfip_t* const ip2) +inline bool SfIp::fast_lt6(const SfIp& ip2) const { const uint32_t* p1, * p2; - p1 = ip1->ip32; - p2 = ip2->ip32; + p1 = ip32; + p2 = ip2.ip32; if (*p1 < *p2) - return 1; + return true; else if (*p1 > *p2) - return 0; + return false; if (p1[1] < p2[1]) - return 1; + return true; else if (p1[1] > p2[1]) - return 0; + return false; if (p1[2] < p2[2]) - return 1; + return true; else if (p1[2] > p2[2]) - return 0; + return false; if (p1[3] < p2[3]) - return 1; + return true; else if (p1[3] > p2[3]) - return 0; + return false; - return 0; + return false; } -inline int sfip_fast_gt6(const sfip_t* const ip1, const sfip_t* const ip2) +inline bool SfIp::fast_gt6(const SfIp& ip2) const { const uint32_t* p1, * p2; - p1 = ip1->ip32; - p2 = ip2->ip32; + p1 = ip32; + p2 = ip2.ip32; if (*p1 > *p2) - return 1; + return true; else if (*p1 < *p2) - return 0; + return false; if (p1[1] > p2[1]) - return 1; + return true; else if (p1[1] < p2[1]) - return 0; + return false; if (p1[2] > p2[2]) - return 1; + return true; else if (p1[2] < p2[2]) - return 0; + return false; if (p1[3] > p2[3]) - return 1; + return true; else if (p1[3] < p2[3]) - return 0; + return false; - return 0; + return false; } -inline int sfip_fast_eq6(const sfip_t* ip1, const sfip_t* ip2) +inline bool SfIp::fast_eq6(const SfIp& ip2) const { const uint32_t* p1, * p2; - p1 = ip1->ip32; - p2 = ip2->ip32; + p1 = ip32; + p2 = ip2.ip32; if (*p1 != *p2) - return 0; + return false; if (p1[1] != p2[1]) - return 0; + return false; if (p1[2] != p2[2]) - return 0; + return false; if (p1[3] != p2[3]) - return 0; - - return 1; -} - -/* Checks if ip2 is equal to ip1 or contained within the CIDR ip1 */ -inline bool sfip_fast_cont4(const sfip_t* ip1, const sfip_t* ip2) -{ - uint32_t shift = 32 - sfip_bits(ip1); - uint32_t ip = ntohl(*ip2->ip32); - - ip >>= shift; - ip <<= shift; - - return ntohl(*ip1->ip32) == ip; -} - -/* Checks if ip2 is equal to ip1 or contained within the CIDR ip1 */ -inline int sfip_fast_cont6(const sfip_t* ip1, const sfip_t* ip2) -{ - uint32_t ip; - int i, bits = sfip_bits(ip1); - int words = bits / 32; - bits = 32 - (bits % 32); - - for ( i = 0; i < words; i++ ) - { - if ( ip1->ip32[i] != ip2->ip32[i] ) - return 0; - } - - if ( bits == 32 ) - return 1; - - ip = ntohl(ip2->ip32[i]); - - ip >>= bits; - ip <<= bits; + return false; - return ntohl(ip1->ip32[i]) == ip; + return true; } -/* Compares two IPs - * Returns 1 for equal and 0 for not equal - */ -inline int sfip_fast_equals_raw(const sfip_t* ip1, const sfip_t* ip2) +inline bool SfIp::fast_equals_raw(const SfIp& ip2) const { int f1,f2; - ARG_CHECK2(ip1, ip2, 0); - - f1 = sfip_family(ip1); - f2 = sfip_family(ip2); + f1 = family; + f2 = ip2.family; if (f1 == AF_INET) { if (f2 != AF_INET) - return 0; - if (sfip_fast_eq4(ip1, ip2)) - return 1; + return false; + if (fast_eq4(ip2)) + return true; } else if (f1 == AF_INET6) { if (f2 != AF_INET6) - return 0; - if (sfip_fast_eq6(ip1, ip2)) - return 1; - } - return 0; -} - -/******************************************************************** - * Function: sfip_is_private() - * - * Checks if the address is local - * - * Arguments: - * sfip_t * - IP address to check - * - * Returns: - * 1 if the IP is in local network - * 0 otherwise - * - ********************************************************************/ -inline int sfip_is_private(const sfip_t* ip) -{ - const unsigned int* p; - - ARG_CHECK1(ip, 0); - - if (sfip_family(ip) == AF_INET) - { - /* - * 10.0.0.0 - 10.255.255.255 (10/8 prefix) - * 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) - * 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) - * */ - return( (ip->ip8[0] == 10) - ||((ip->ip8[0] == 172) && ((ip->ip8[1] & 0xf0 ) == 16)) - ||((ip->ip8[0] == 192) && (ip->ip8[1] == 168)) ); - } - - p = ip->ip32; - - /* Check the first 64 bits in an IPv6 address, and - verify they're zero. If not, it's not a loopback */ - if (p[0] || p[1]) - return 0; - - /* Check if the 3rd 32-bit int is zero */ - if ( p[2] == 0 ) - { - /* ::ipv4 compatible ipv6 - ::1 is the IPv6 loopback */ - return ( (ip->ip8[12] == 10) - ||((ip->ip8[12] == 172) && ((ip->ip8[13] & 0xf0 ) == 16)) - ||((ip->ip8[12] == 192) && (ip->ip8[13] == 168)) - || (ntohl(p[3]) == 0x1) ); + return false; + if (fast_eq6(ip2)) + return true; } - /* Check the 3rd 32-bit int for a mapped IPv4 address */ - if ( ntohl(p[2]) == 0xffff ) - { - /* ::ffff: IPv4 loopback mapped over IPv6 */ - return ( (ip->ip8[12] == 10) - ||((ip->ip8[12] == 172) && ((ip->ip8[13] & 0xf0 ) == 16)) - ||((ip->ip8[12] == 192) && (ip->ip8[13] == 168)) ); - } - return 0; + return false; } -/* Returns 1 if the IP is non-zero. 0 otherwise * - * XXX This is a performance critical function, - * need to determine if it's safe to not check these pointers - * - * SNORT RELIC - */ -inline int sfip_is_set(const sfip_t* const ip) -{ -// ARG_CHECK1(ip, -1); - return ip->ip32[0] || - ( (ip->family == AF_INET6) && - (ip->ip32[1] || - ip->ip32[2] || - ip->ip32[3] || ip->bits != 128)) || ((ip->family == AF_INET) && ip->bits != 32); -} +/* End of member function definitions */ -inline int sfip_is_set(const sfip_t& ip) -{ -// ARG_CHECK1(ip, -1); - return ip.ip32[0] || - ( (ip.family == AF_INET6) && - (ip.ip32[1] || - ip.ip32[2] || - ip.ip32[3] || ip.bits != 128)) || ((ip.family == AF_INET) && ip.bits != 32); -} - -inline bool _is_sfip_equals(const sfip_t* const lhs, const sfip_t* const rhs) -{ - if (lhs->is_ip4()) - { - return (rhs->is_ip4()) && - (lhs->ip32[0] == rhs->ip32[0]); - } - else if (lhs->is_ip6()) - { - return (rhs->is_ip6()) && - (lhs->ip32[0] == rhs->ip32[0]) && - (lhs->ip32[1] == rhs->ip32[1]) && - (lhs->ip32[2] == rhs->ip32[2]) && - (lhs->ip32[3] == rhs->ip32[3]); - } - else - { - return false; - } -} - -inline bool _is_sfip_lesser(const sfip_t* const lhs, const sfip_t* const rhs) -{ - if (lhs->is_ip4()) - { - return (rhs->is_ip4() && - (htonl(lhs->ip32[0]) < htonl(rhs->ip32[0]))); - } - else if (lhs->is_ip6()) - { - return (rhs->is_ip6() && - (htonl(lhs->ip32[0]) < htonl(rhs->ip32[0])) && - (htonl(lhs->ip32[1]) < htonl(rhs->ip32[1])) && - (htonl(lhs->ip32[2]) < htonl(rhs->ip32[2])) && - (htonl(lhs->ip32[3]) < htonl(rhs->ip32[3]))); - } - else - { - return false; - } -} - -inline bool sfip_equals(const sfip_t* const lhs, const sfip_t* const rhs) -{ - if (!sfip_is_set(lhs) || !sfip_is_set(rhs)) - return true; - - return _is_sfip_equals(lhs, rhs); -} - -inline bool sfip_not_equals(const sfip_t* const lhs, const sfip_t* const rhs) -{ return !sfip_equals(lhs,rhs); } - -inline bool sfip_unset_equals(const sfip_t* const lhs, const sfip_t* const rhs) -{ - if (!sfip_is_set(lhs) || !sfip_is_set(rhs)) - return false; - - return _is_sfip_equals(lhs, rhs); -} - -inline bool sfip_lesser(const sfip_t* const lhs, const sfip_t* const rhs) -{ - // I'm copying and pasting. Don't ask me why this is different then sfip_equals - if (!sfip_is_set(lhs) || !sfip_is_set(rhs)) - return false; - - return _is_sfip_lesser(lhs, rhs); -} - -inline bool sfip_greater(const sfip_t* const lhs, const sfip_t* const rhs) -{ - // I'm copying and pasting. Don't ask me why this is different then sfip_equals - if (!sfip_is_set(lhs) || !sfip_is_set(rhs)) - return false; - - return _is_sfip_lesser(rhs, lhs); -} - -inline void sfip_clear(sfip_t& x) -{ - x.family = 0; - x.bits = 0; - x.ip32[0] = 0; - x.ip32[1] = 0; - x.ip32[2] = 0; - x.ip32[3] = 0; -} - -/* - * This is the former macro IP_COPY_VALUE(x, y). No need to assign - * specific operator since the default equals operator will - * correctly assign values - */ -inline void sfip_copy(sfip_t& lhs, const sfip_t* const rhs) -{ lhs = *rhs; } - -#if 0 -#define sfip_equals(x,y) (sfip_compare(&x, &y) == SFIP_EQUAL) -#define sfip_not_equals !sfip_equals -#define sfip_clear(x) memset(x, 0, 16) -#endif - -/* Printing ************************************************************/ /* Uses a static buffer to return a string representation of the IP */ -SO_PUBLIC void sfip_raw_ntop(int family, const void* ip_raw, char* buf, int bufsize); -SO_PUBLIC void sfip_ntop(const sfip_t* ip, char* buf, int bufsize); +SO_PUBLIC void sfip_ntop(const SfIp* ip, char* buf, int bufsize); -inline std::ostream& operator<<(std::ostream& os, const sfip_t* addr) +inline std::ostream& operator<<(std::ostream& os, const SfIp* addr) { char str[INET6_ADDRSTRLEN]; sfip_ntop(addr, str, sizeof(str)); @@ -713,5 +463,9 @@ inline std::ostream& operator<<(std::ostream& os, const sfip_t* addr) return os; } + +// FIXIT-L X This should be in utils_net if anywhere, but that makes it way harder to link into unit tests +SO_PUBLIC void snort_inet_ntop(int family, const void* ip_raw, char* buf, int bufsize); + #endif diff --git a/src/sfip/sf_ipvar.cc b/src/sfip/sf_ipvar.cc index 6f84aa8ff..441bcf1ea 100644 --- a/src/sfip/sf_ipvar.cc +++ b/src/sfip/sf_ipvar.cc @@ -32,12 +32,14 @@ #include #include "utils/util.h" -#include "sfip/sf_vartable.h" + +#include "sf_cidr.h" +#include "sf_vartable.h" #define LIST_OPEN '[' #define LIST_CLOSE ']' -static SFIP_RET sfvar_list_compare(sfip_node_t*, sfip_node_t*); +static SfIpRet sfvar_list_compare(sfip_node_t*, sfip_node_t*); static inline void sfip_node_free(sfip_node_t*); static inline void sfip_node_freelist(sfip_node_t*); @@ -71,11 +73,12 @@ void sfvar_free(sfip_var_t* var) } /* Allocaties and returns an IP node described by 'str' */ -static sfip_node_t* sfipnode_alloc(const char* str, SFIP_RET* status) +static sfip_node_t* sfipnode_alloc(const char* str, SfIpRet* status) { // FIXIT-L rename variables from ret to something with more descriptive // this code smell that afflicts 55 source files and all should be fixed sfip_node_t* ret; + SfIpRet rc; if (!str) { @@ -111,45 +114,36 @@ static sfip_node_t* sfipnode_alloc(const char* str, SFIP_RET* status) ret->flags |= SFIP_ANY; - if ( (ret->ip = sfip_alloc("0.0.0.0", status)) == NULL ) + ret->ip = new SfCidr(); + if ((rc = ret->ip->set("0.0.0.0")) != SFIP_SUCCESS) { - /* Failed to parse this string, so free and return */ if (status) - *status = SFIP_ALLOC_ERR; - - snort_free(ret); + *status = rc; + sfip_node_free(ret); return NULL; } if (status) *status = SFIP_SUCCESS; - -#if 0 - if ( (ret->ip = sfip_alloc("0.0.0.0", NULL)) == NULL) + } + else + { + ret->ip = new SfCidr(); + if ((rc = ret->ip->set(str)) != SFIP_SUCCESS) { if (status) - *status = SFIP_FAILURE; - snort_free(ret); + *status = rc; + sfip_node_free(ret); return NULL; } -#endif - } - else if ( (ret->ip = sfip_alloc(str, status)) == NULL ) - { - /* Failed to parse this string, so free and return */ - if (status) - *status = SFIP_INET_PARSE_ERR; - snort_free(ret); - return NULL; } /* Check if this is a negated, zero'ed IP (equivalent of a "!any") */ - if (!sfip_is_set(ret->ip) && (ret->flags & SFIP_NEGATED)) + if (!ret->ip->is_set() && (ret->flags & SFIP_NEGATED)) { if (status) *status = SFIP_NOT_ANY; - snort_free(ret->ip); - snort_free(ret); + sfip_node_free(ret); return NULL; } @@ -162,7 +156,7 @@ static inline void sfip_node_free(sfip_node_t* node) return; if ( node->ip ) - sfip_free(node->ip); + delete node->ip; snort_free(node); } @@ -191,15 +185,15 @@ static inline sfip_node_t* _sfvar_deep_copy_list(const sfip_node_t* idx) { prev = temp; - temp = (sfip_node_t*)snort_calloc(sizeof(sfip_node_t)); - temp->ip = (sfip_t*)snort_calloc(sizeof(sfip_t)); + temp = (sfip_node_t*)snort_calloc(sizeof(*temp)); + temp->ip = new SfCidr(); temp->flags = idx->flags; temp->addr_flags = idx->addr_flags; /* If it's an "any", there may be no IP object */ if (idx->ip) - memcpy(temp->ip, idx->ip, sizeof(sfip_t)); + memcpy(temp->ip, idx->ip, sizeof(*temp->ip)); if (prev) prev->next = temp; @@ -217,7 +211,7 @@ static sfip_var_t* sfvar_deep_copy(const sfip_var_t* var) if (!var) return NULL; - ret = (sfip_var_t*)snort_calloc(sizeof(sfip_var_t)); + ret = (sfip_var_t*)snort_calloc(sizeof(*ret)); ret->mode = var->mode; ret->head = _sfvar_deep_copy_list(var->head); @@ -228,7 +222,7 @@ static sfip_var_t* sfvar_deep_copy(const sfip_var_t* var) /* Deep copy of src added to dst Ordering is not necessarily preserved */ -static SFIP_RET sfvar_add(sfip_var_t* dst, sfip_var_t* src) +static SfIpRet sfvar_add(sfip_var_t* dst, sfip_var_t* src) { sfip_node_t* oldhead, * oldneg, * idx; sfip_var_t* copiedvar; @@ -279,7 +273,7 @@ static SFIP_RET sfvar_add(sfip_var_t* dst, sfip_var_t* src) /* Adds the nodes in 'src' to the variable 'dst' */ /* The mismatch of types is for ease-of-supporting Snort4 and * Snort6 simultaneously */ -static SFIP_RET sfvar_add_node(sfip_var_t* var, sfip_node_t* node, int negated) +static SfIpRet sfvar_add_node(sfip_var_t* var, sfip_node_t* node, int negated) { sfip_node_t* p; sfip_node_t* swp; @@ -306,7 +300,7 @@ static SFIP_RET sfvar_add_node(sfip_var_t* var, sfip_node_t* node, int negated) /* "Anys" should always be inserted first Otherwise, check if this IP is less than the head's IP */ if ((node->flags & SFIP_ANY) || - (sfip_compare(node->ip, (*head)->ip) == SFIP_LESSER)) + node->ip->get_addr()->compare(*(*head)->ip->get_addr()) == SFIP_LESSER) { node->next = *head; *head = node; @@ -325,7 +319,7 @@ static SFIP_RET sfvar_add_node(sfip_var_t* var, sfip_node_t* node, int negated) /* Insertion sort */ for (p = *head; p->next; p=p->next) { - if (sfip_compare(node->ip, p->next->ip) == SFIP_LESSER) + if (node->ip->get_addr()->compare(*p->next->ip->get_addr()) == SFIP_LESSER) { swp = p->next; p->next = node; @@ -370,7 +364,7 @@ static int sfvar_is_alias(const sfip_var_t* one, const sfip_var_t* two) return 0; } -static SFIP_RET sfvar_list_compare(sfip_node_t* list1, sfip_node_t* list2) +static SfIpRet sfvar_list_compare(sfip_node_t* list1, sfip_node_t* list2) { int total1 = 0; int total2 = 0; @@ -407,7 +401,7 @@ static SFIP_RET sfvar_list_compare(sfip_node_t* list1, sfip_node_t* list2) for (tmp2 = list2, i = 0; tmp2 != NULL; tmp2 = tmp2->next, i++) { - if ((sfip_compare(tmp->ip, tmp2->ip) == SFIP_EQUAL) && !usage[i]) + if ((tmp->ip->get_addr()->compare(*tmp2->ip->get_addr()) == SFIP_EQUAL) && !usage[i]) { match = 1; usage[i] = 1; @@ -427,7 +421,7 @@ static SFIP_RET sfvar_list_compare(sfip_node_t* list1, sfip_node_t* list2) } /* Check's if two variables have the same nodes */ -SFIP_RET sfvar_compare(const sfip_var_t* one, const sfip_var_t* two) +SfIpRet sfvar_compare(const sfip_var_t* one, const sfip_var_t* two) { /* If both NULL, consider equal */ if (!one && !two) @@ -509,12 +503,12 @@ static void _negate_lists(sfip_var_t* var) var->neg_head = temp; } -SFIP_RET sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, +SfIpRet sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, const char* str, int negation) { const char* end; char* tok; - SFIP_RET ret; + SfIpRet ret; int neg_ip; if (!var || !table || !str) @@ -595,7 +589,7 @@ SFIP_RET sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, } /* Check if this is a negated, zero'ed IP (equivalent of a "!any") */ - if (copy_var->head && !sfip_is_set(copy_var->head->ip)) + if (copy_var->head && !copy_var->head->ip->is_set()) { snort_free(tok); sfvar_free(copy_var); @@ -650,7 +644,7 @@ SFIP_RET sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, } /* Check if this is a negated, zero'ed IP (equivalent of a "!any") */ - if (!sfip_is_set(node->ip) && (node->flags & SFIP_NEGATED)) + if (!node->ip->is_set() && (node->flags & SFIP_NEGATED)) { sfip_node_free(node); snort_free(tok); @@ -676,7 +670,7 @@ SFIP_RET sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, return SFIP_SUCCESS; } -SFIP_RET sfvar_validate(sfip_var_t* var) +SfIpRet sfvar_validate(sfip_var_t* var) { sfip_node_t* idx, * neg_idx; @@ -688,9 +682,9 @@ SFIP_RET sfvar_validate(sfip_var_t* var) for (neg_idx = var->neg_head; neg_idx; neg_idx = neg_idx->next) { /* A smaller netmask means "less specific" */ - if ((sfip_bits(neg_idx->ip) <= sfip_bits(idx->ip)) && + if ((neg_idx->ip->get_bits() <= idx->ip->get_bits()) && /* Verify they overlap */ - (sfip_contains(neg_idx->ip, idx->ip) == SFIP_CONTAINS)) + (neg_idx->ip->contains(idx->ip->get_addr()) == SFIP_CONTAINS)) { return SFIP_CONFLICT; } @@ -701,12 +695,12 @@ SFIP_RET sfvar_validate(sfip_var_t* var) } /* Allocates and returns a new variable, described by "variable". */ -sfip_var_t* sfvar_alloc(vartable_t* table, const char* variable, SFIP_RET* status) +sfip_var_t* sfvar_alloc(vartable_t* table, const char* variable, SfIpRet* status) { sfip_var_t* ret, * tmpvar; const char* str, * end; char* tmp; - SFIP_RET stat; + SfIpRet stat; if (!variable || !(*variable)) { @@ -830,7 +824,7 @@ sfip_var_t* sfvar_alloc(vartable_t* table, const char* variable, SFIP_RET* statu } /* Support function for sfvar_ip_in */ -static inline bool sfvar_ip_in4(sfip_var_t* var, const sfip_t* ip) +static inline bool sfvar_ip_in4(sfip_var_t* var, const SfIp* ip) { int match; sfip_node_t* pos_idx, * neg_idx; @@ -844,10 +838,10 @@ static inline bool sfvar_ip_in4(sfip_var_t* var, const sfip_t* ip) { for (; neg_idx; neg_idx = neg_idx->next) { - if (sfip_family(neg_idx->ip) != AF_INET) + if (neg_idx->ip->get_addr()->get_family() != AF_INET) continue; - if (sfip_fast_cont4(neg_idx->ip, ip)) + if (neg_idx->ip->fast_cont4(*ip)) return false; } @@ -858,8 +852,8 @@ static inline bool sfvar_ip_in4(sfip_var_t* var, const sfip_t* ip) { if (neg_idx) { - if (sfip_family(neg_idx->ip) == AF_INET && - sfip_fast_cont4(neg_idx->ip, ip)) + if (neg_idx->ip->get_addr()->get_family() == AF_INET && + neg_idx->ip->fast_cont4(*ip)) { return false; } @@ -874,10 +868,10 @@ static inline bool sfvar_ip_in4(sfip_var_t* var, const sfip_t* ip) if (!match) { - if (sfip_is_set(pos_idx->ip)) + if (pos_idx->ip->is_set()) { - if (sfip_family(pos_idx->ip) == AF_INET && - sfip_fast_cont4(pos_idx->ip, ip)) + if (pos_idx->ip->get_addr()->get_family() == AF_INET && + pos_idx->ip->fast_cont4(*ip)) { match = 1; } @@ -897,7 +891,7 @@ static inline bool sfvar_ip_in4(sfip_var_t* var, const sfip_t* ip) } /* Support function for sfvar_ip_in */ -static inline bool sfvar_ip_in6(sfip_var_t* var, const sfip_t* ip) +static inline bool sfvar_ip_in6(sfip_var_t* var, const SfIp* ip) { int match; sfip_node_t* pos_idx, * neg_idx; @@ -911,10 +905,10 @@ static inline bool sfvar_ip_in6(sfip_var_t* var, const sfip_t* ip) { for (; neg_idx; neg_idx = neg_idx->next) { - if (sfip_family(neg_idx->ip) != AF_INET6) + if (neg_idx->ip->get_addr()->get_family() != AF_INET6) continue; - if (sfip_fast_cont6(neg_idx->ip, ip)) + if (neg_idx->ip->fast_cont6(*ip)) return false; } @@ -925,8 +919,8 @@ static inline bool sfvar_ip_in6(sfip_var_t* var, const sfip_t* ip) { if (neg_idx) { - if (sfip_family(neg_idx->ip) == AF_INET6 && - sfip_fast_cont6(neg_idx->ip, ip)) + if (neg_idx->ip->get_addr()->get_family() == AF_INET6 && + neg_idx->ip->fast_cont6(*ip)) { return false; } @@ -941,10 +935,10 @@ static inline bool sfvar_ip_in6(sfip_var_t* var, const sfip_t* ip) if (!match) { - if (sfip_is_set(pos_idx->ip)) + if (pos_idx->ip->is_set()) { - if (sfip_family(pos_idx->ip) == AF_INET6 && - sfip_fast_cont6(pos_idx->ip, ip)) + if (pos_idx->ip->get_addr()->get_family() == AF_INET6 && + pos_idx->ip->fast_cont6(*ip)) { match = 1; } @@ -963,7 +957,7 @@ static inline bool sfvar_ip_in6(sfip_var_t* var, const sfip_t* ip) return false; } -bool sfvar_ip_in(sfip_var_t* var, const sfip_t* ip) +bool sfvar_ip_in(sfip_var_t* var, const SfIp* ip) { if (!var || !ip) return false; @@ -972,7 +966,7 @@ bool sfvar_ip_in(sfip_var_t* var, const sfip_t* ip) * codepaths for IPv6 and IPv4 traffic, rather than the dual-stack * functions. */ - if (sfip_family(ip) == AF_INET) + if (ip->get_family() == AF_INET) { return sfvar_ip_in4(var, ip); } diff --git a/src/sfip/sf_ipvar.h b/src/sfip/sf_ipvar.h index 35f136c41..ed462e012 100644 --- a/src/sfip/sf_ipvar.h +++ b/src/sfip/sf_ipvar.h @@ -34,7 +34,12 @@ #define SFIP_ANY 2 #include -#include "sfip/sf_ip.h" +#include + +#include "sfip/sf_returns.h" + +struct SfIp; +struct SfCidr; /* Selects which mode a given variable is using to * store and lookup IP addresses */ @@ -44,10 +49,10 @@ typedef enum _modes SFIP_TABLE } MODES; -/* Used by the "list" mode. A doubly linked list of sfip_t objects. */ +/* Used by the "list" mode. A doubly linked list of SfIp objects. */ typedef struct _ip_node { - sfip_t* ip; + SfCidr* ip; #define ip_addr ip; /* To ease porting Snort */ struct _ip_node* next; int flags; @@ -94,23 +99,23 @@ struct vartable_t sfip_var_t* sfvar_create_alias(const sfip_var_t* alias_from, const char* alias_to); /* Allocates a new variable as according to "str" */ -sfip_var_t* sfvar_alloc(vartable_t* table, const char* str, SFIP_RET* status); +sfip_var_t* sfvar_alloc(vartable_t* table, const char* str, SfIpRet* status); /* Makes sure there are no IP address conflicts in the variable Returns SFIP_CONFLICT if so */ -SFIP_RET sfvar_validate(sfip_var_t* var); +SfIpRet sfvar_validate(sfip_var_t* var); /* Parses an IP list described by 'str' and saves the results in 'var'. */ -SFIP_RET sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, +SfIpRet sfvar_parse_iplist(vartable_t* table, sfip_var_t* var, const char* str, int negation); /* Compares two variables. Necessary when building RTN structure */ -SFIP_RET sfvar_compare(const sfip_var_t* one, const sfip_var_t* two); +SfIpRet sfvar_compare(const sfip_var_t* one, const sfip_var_t* two); /* Free an allocated variable */ void sfvar_free(sfip_var_t* var); // returns true if both args are valid and ip is contained by var -bool sfvar_ip_in(sfip_var_t* var, const sfip_t* ip); +bool sfvar_ip_in(sfip_var_t* var, const SfIp* ip); #endif diff --git a/src/sfip/sf_returns.h b/src/sfip/sf_returns.h index 05a989786..23d405b5a 100644 --- a/src/sfip/sf_returns.h +++ b/src/sfip/sf_returns.h @@ -20,7 +20,7 @@ #ifndef SF_RETURNS_H #define SF_RETURNS_H -enum SFIP_RET +enum SfIpRet { SFIP_SUCCESS=0, SFIP_FAILURE, diff --git a/src/sfip/sf_vartable.cc b/src/sfip/sf_vartable.cc index 046c8e3a9..a94b722e2 100644 --- a/src/sfip/sf_vartable.cc +++ b/src/sfip/sf_vartable.cc @@ -39,6 +39,10 @@ #include "sfip/sf_ipvar.h" #include "utils/util.h" +#ifdef UNIT_TEST +#include "catch/catch.hpp" +#endif + vartable_t* sfvt_alloc_table() { vartable_t* table = (vartable_t*)snort_calloc(sizeof(vartable_t)); @@ -181,12 +185,12 @@ sfvt_expand_value_error: // XXX this implementation is just used to support // Snort's underlying implementation better -SFIP_RET sfvt_define(vartable_t* table, const char* name, const char* value) +SfIpRet sfvt_define(vartable_t* table, const char* name, const char* value) { char* buf; int len; sfip_var_t* ipret = NULL; - SFIP_RET ret; + SfIpRet ret; if (!name || !value) return SFIP_ARG_ERR; @@ -203,13 +207,13 @@ SFIP_RET sfvt_define(vartable_t* table, const char* name, const char* value) } /* Adds the variable described by "str" to the table "table" */ -SFIP_RET sfvt_add_str(vartable_t* table, const char* str, sfip_var_t** ipret) +SfIpRet sfvt_add_str(vartable_t* table, const char* str, sfip_var_t** ipret) { sfip_var_t* var; sfip_var_t* swp; sfip_var_t* p; int ret; - SFIP_RET status = SFIP_FAILURE; + SfIpRet status = SFIP_FAILURE; if (!table || !str || !ipret) return SFIP_FAILURE; @@ -291,9 +295,9 @@ SFIP_RET sfvt_add_str(vartable_t* table, const char* str, sfip_var_t** ipret) /* Adds the variable described by "src" to the variable "dst", * using the vartable for looking variables used within "src" */ -SFIP_RET sfvt_add_to_var(vartable_t* table, sfip_var_t* dst, const char* src) +SfIpRet sfvt_add_to_var(vartable_t* table, sfip_var_t* dst, const char* src) { - SFIP_RET ret; + SfIpRet ret; if (!table || !dst || !src) return SFIP_ARG_ERR; @@ -352,82 +356,70 @@ void sfvt_free_table(vartable_t* table) snort_free(table); } -/* Prints a table's contents */ -//#define TESTER +// FIXIT-L - Finish converting these unit tests to something that actually passes +#if 0 +#ifdef UNIT_TEST -#ifdef TESTER -int failures = 0; -#define TEST(x) \ - if (x) printf("\tSuccess: line %d\n", __LINE__); \ - else { printf("\tFAILURE: line %d\n", __LINE__); failures++; } - -int main() +TEST_CASE("SfVarTable_Kitchen_Sink", "[SfVarTable]") { vartable_t* table; sfip_var_t* var; - sfip_t* ip; + SfIp* ip; + SfIpRet status; - puts("********************************************************************"); - puts("Testing variable table parsing:"); table = sfvt_alloc_table(); + + /* Parsing tests */ /* These are all valid */ - TEST(sfvt_add_str(table, "foo [ 1.2.0.0/16, ffff:dead:beef::0 ] ", &var) == SFIP_SUCCESS); - TEST(sfvt_add_str(table, " goo [ ffff:dead:beef::0 ] ", &var) == SFIP_SUCCESS); - TEST(sfvt_add_str(table, " moo [ any ] ", &var) == SFIP_SUCCESS); + CHECK(sfvt_add_str(table, "foo [ 1.2.0.0/16, ffff:dead:beef::0 ] ", &var) == SFIP_SUCCESS); + CHECK(sfvt_add_str(table, " goo [ ffff:dead:beef::0 ] ", &var) == SFIP_SUCCESS); + CHECK(sfvt_add_str(table, " moo [ any ] ", &var) == SFIP_SUCCESS); /* Test variable redefine */ - TEST(sfvt_add_str(table, " goo [ 192.168.0.1, 192.168.0.2, 192.168.255.0 255.255.248.0 ] ", + CHECK(sfvt_add_str(table, " goo [ 192.168.0.1, 192.168.0.2, 192.168.255.0 255.255.248.0 ] ", &var) == SFIP_DUPLICATE); /* These should fail since it's a variable name with bogus arguments */ - TEST(sfvt_add_str(table, " phlegm ", &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, " phlegm [", &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, " phlegm [ ", &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, " phlegm [sdfg ", &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, " phlegm [ sdfg, 12.123.1.4.5 }", &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, " [ 12.123.1.4.5 ]", &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, NULL, &var) == SFIP_FAILURE); - TEST(sfvt_add_str(table, "", &var) == SFIP_FAILURE); - - puts(""); - puts("********************************************************************"); + CHECK(sfvt_add_str(table, " phlegm ", &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, " phlegm [", &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, " phlegm [ ", &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, " phlegm [sdfg ", &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, " phlegm [ sdfg, 12.123.1.4.5 }", &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, " [ 12.123.1.4.5 ]", &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, NULL, &var) == SFIP_FAILURE); + CHECK(sfvt_add_str(table, "", &var) == SFIP_FAILURE); + + /* Expansion tests puts("Expansions:"); - /* Note: used this way leaks memory */ printf("\t%s\n", sfvt_alloc_expanded(table, "$foo")); printf("\t%s\n", sfvt_alloc_expanded(table, "goo $goo sf sfasdfasdf $moo")); printf("\t%s\n", sfvt_alloc_expanded(table, " ssdf $moo $moo asdf $fooadff $foo ")); printf("\t%s\n", sfvt_alloc_expanded(table, " ssdf $moo $moo\\sdf $foo adff")); + */ - puts(""); - puts("********************************************************************"); - puts("Containment checks:"); - var = sfvt_lookup(table, "goo"); - ip = sfip_alloc("192.168.248.255"); - TEST(sfvar_ip_in(var, ip)); + /* Containment tests */ + var = sfvt_lookup_var(table, "goo"); + ip = sfip_alloc("192.168.248.255", &status); + CHECK(sfvar_ip_in(var, ip)); /* Check against the 'any' variable */ var = sfvt_lookup_var(table, "moo"); - TEST(sfvar_ip_in(var, ip)); + CHECK(sfvar_ip_in(var, ip)); /* Verify it's not in this variable */ var = sfvt_lookup_var(table, "foo"); - TEST(!sfvar_ip_in(var, ip)); + CHECK(!sfvar_ip_in(var, ip)); /* Check boundary cases */ var = sfvt_lookup_var(table, "goo"); - free_ip(ip); - ip = sfip_alloc_str("192.168.0.3"); - TEST(!sfvar_ip_in(var, ip)); - free_ip(ip); - ip = sfip_alloc_str("192.168.0.2"); - TEST(sfvar_ip_in(var, ip)); - - puts(""); - puts("********************************************************************"); - - printf("\n\tTotal Failures: %d\n", failures); - return 0; + sfip_free(ip); + ip = sfip_alloc("192.168.0.3", &status); + CHECK(!sfvar_ip_in(var, ip)); + sfip_free(ip); + ip = sfip_alloc("192.168.0.2", &status); + CHECK(sfvar_ip_in(var, ip)); + sfip_free(ip); } #endif - +#endif diff --git a/src/sfip/sf_vartable.h b/src/sfip/sf_vartable.h index bb8684f54..da9538e35 100644 --- a/src/sfip/sf_vartable.h +++ b/src/sfip/sf_vartable.h @@ -31,6 +31,7 @@ // Library for implementing a variable table. #include + #include "sfip/sf_returns.h" struct sfip_var_t; @@ -41,12 +42,12 @@ vartable_t* sfvt_alloc_table(); void sfvt_free_table(vartable_t* table); /* Adds the variable described by "str" to the table "table" */ -SFIP_RET sfvt_add_str(vartable_t* table, const char* str, sfip_var_t**); -SFIP_RET sfvt_define(vartable_t* table, const char* name, const char* value); +SfIpRet sfvt_add_str(vartable_t* table, const char* str, sfip_var_t**); +SfIpRet sfvt_define(vartable_t* table, const char* name, const char* value); /* Adds the variable described by "str" to the variable "dst", * using the vartable for looking variables used within "str" */ -SFIP_RET sfvt_add_to_var(vartable_t* table, sfip_var_t* dst, const char* src); +SfIpRet sfvt_add_to_var(vartable_t* table, sfip_var_t* dst, const char* src); /* Looks up a variable from the table using the name as the key */ sfip_var_t* sfvt_lookup_var(vartable_t* table, const char* name); diff --git a/src/sfip/sfip_t.h b/src/sfip/sfip_t.h deleted file mode 100644 index 2196366d2..000000000 --- a/src/sfip/sfip_t.h +++ /dev/null @@ -1,85 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (C) 2014-2016 Cisco and/or its affiliates. All rights reserved. -// Copyright (C) 1998-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. -//-------------------------------------------------------------------------- - -/* - * Adam Keeton - * sfip_t.h - * 11/17/06 -*/ - -#ifndef SFIP_SFIP_T_H -#define SFIP_SFIP_T_H - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include -#include -#include -#include -#include - -#include "main/snort_types.h" - -/* factored out for attribute table */ - -struct sfip_t -{ - int16_t family; - int16_t bits; - - /* see sfip_size(): these address bytes - * must be the last field in this struct */ - union - { - uint8_t ip8[16]; - uint16_t ip16[8]; - uint32_t ip32[4]; -/* uint64_t ip64[2]; */ - }; - - inline void clear() - { - family = bits = 0; - ip32[0] = ip32[1] = ip32[2] = ip32[3] = 0; - } - - inline bool is_ip6() const - { return family == AF_INET6; } - - inline bool is_ip4() const - { return family == AF_INET; } - - // the '+ 4' is the int32_t IPv4 address - inline std::size_t sfip_size() const - { return is_ip6() ? sizeof(sfip_t) : offsetof(sfip_t, ip8) + 4; } -}; - -// This is leftover from Snort which we're stuck with -#ifdef inet_ntoa -#undef inet_ntoa -#endif -// FIXIT-H replace all inet_ntoa() with sfip_to_str() and delete redef -SO_PUBLIC char* sfip_to_str(const sfip_t*); -#define sfip_ntoa(x) sfip_to_str(x) -#define inet_ntoa sfip_ntoa - -#endif - diff --git a/src/sfip/sfip_test.cc b/src/sfip/sfip_test.cc index b9dbe758b..a83e1dd60 100644 --- a/src/sfip/sfip_test.cc +++ b/src/sfip/sfip_test.cc @@ -28,7 +28,7 @@ #include "catch/unit_test.h" #include "main/snort_types.h" -#include "sf_ip.h" +#include "sf_cidr.h" //--------------------------------------------------------------- @@ -73,17 +73,17 @@ static FuncTest ftests[] = { "sfip_pton", "255.255.255.255/21", "255.255.248.0", SFIP_SUCCESS }, { "sfip_pton", "1.1.255.255 255.255.248.0", "1.1.248.0", SFIP_SUCCESS }, { "sfip_pton", " 2001:0db8:0000:0000:0000:0000:1428:57ab ", - "2001:db8::1428:57ab", SFIP_SUCCESS }, + "2001:0db8:0000:0000:0000:0000:1428:57ab", SFIP_SUCCESS }, { "sfip_pton", "ffff:ffff::1", - "ffff:ffff::1", SFIP_SUCCESS }, + "ffff:ffff:0000:0000:0000:0000:0000:0001", SFIP_SUCCESS }, { "sfip_pton", "fFfF::FfFf:FFFF/127", - "ffff::ffff:fffe", SFIP_SUCCESS }, + "ffff:0000:0000:0000:0000:0000:ffff:fffe", SFIP_SUCCESS }, { "sfip_pton", "ffff::ffff:1/8", - "ff00::", SFIP_SUCCESS }, + "ff00:0000:0000:0000:0000:0000:0000:0000", SFIP_SUCCESS }, { "sfip_pton", "6543:21ff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ff00::", - "6543:2100::", SFIP_SUCCESS }, + "6543:2100:0000:0000:0000:0000:0000:0000", SFIP_SUCCESS }, { "sfip_pton", "ffee:ddcc:bbaa:9988:7766:5544:3322:1100/32", - "ffee:ddcc::", SFIP_SUCCESS }, + "ffee:ddcc:0000:0000:0000:0000:0000:0000", SFIP_SUCCESS }, { "sfip_pton", "ffee:ddcc:bbaa:9988:7766:5544:3322:1100", "ffee:ddcc:bbaa:9988:7766:5544:3322:1100", SFIP_SUCCESS }, { "sfip_pton", "1.2.3.4:255.0.0.0", "1.0.0.0", SFIP_SUCCESS }, @@ -96,28 +96,27 @@ static FuncTest ftests[] = { "sfip_pton", "1.2.3.4/ 16", "1.2.0.0", SFIP_SUCCESS }, { "sfip_pton", "1.2.3.4 / 16", "1.2.0.0", SFIP_SUCCESS }, { "sfip_pton", " 1.2.3.4 / 16 ", "1.2.0.0", SFIP_SUCCESS }, + { "sfip_pton", "1.2.3.4/0", "0.0.0.0", SFIP_SUCCESS }, + { "sfip_pton", "1.2.3.4/16", "1.2.0.0", SFIP_SUCCESS }, { "sfip_pton", "1234::1.2.3.4", - "1234::102:304", SFIP_SUCCESS }, + "1234:0000:0000:0000:0000:0000:0102:0304", SFIP_SUCCESS }, { "sfip_pton", "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210", "fedc:ba98:7654:3210:fedc:ba98:7654:3210", SFIP_SUCCESS }, { "sfip_pton", "1080:0:0:0:8:800:200C:4171", - "1080::8:800:200c:4171", SFIP_SUCCESS }, + "1080:0000:0000:0000:0008:0800:200c:4171", SFIP_SUCCESS }, { "sfip_pton", "3ffe:2a00:100:7031::1", - "3ffe:2a00:100:7031::1", SFIP_SUCCESS }, + "3ffe:2a00:0100:7031:0000:0000:0000:0001", SFIP_SUCCESS }, { "sfip_pton", "1080::8:800:200C:417A", - "1080::8:800:200c:417a", SFIP_SUCCESS }, + "1080:0000:0000:0000:0008:0800:200c:417a", SFIP_SUCCESS }, { "sfip_pton", "::192.9.5.5", - "::192.9.5.5", SFIP_SUCCESS }, + "0000:0000:0000:0000:0000:0000:c009:0505", SFIP_SUCCESS }, { "sfip_pton", "::FFFF:129.144.52.38", - "::ffff:129.144.52.38", SFIP_SUCCESS }, - { "sfip_pton", "2010:836B:4179::836B:4179", - "2010:836b:4179::836b:4179", SFIP_SUCCESS }, - { "sfip_pton", "::", "::", SFIP_SUCCESS }, + "0000:0000:0000:0000:0000:ffff:8190:3426", SFIP_SUCCESS }, - // atoi(arg2) gives expected hash length - // ip format ensures alloc tests don't fail - { "sfip_size", "::", "20.0.0.0", SFIP_SUCCESS }, - { "sfip_size", "1.2.3.4", "8.0.0.0", SFIP_SUCCESS }, + { "sfip_pton", "2010:836B:4179::836B:4179", + "2010:836b:4179:0000:0000:0000:836b:4179", SFIP_SUCCESS }, + { "sfip_pton", "::", + "0000:0000:0000:0000:0000:0000:0000:0000", SFIP_SUCCESS }, { "sfip_is_set", "8::", NULL, SFIP_SUCCESS }, { "sfip_is_set", "::1", NULL, SFIP_SUCCESS }, @@ -138,11 +137,12 @@ static FuncTest ftests[] = { "sfip_ismapped", "8::ffff:c000:280", NULL, SFIP_FAILURE }, { "sfip_ismapped", "::fffe:c000:280", NULL, SFIP_FAILURE }, - { "_ip6_cmp", "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8", SFIP_EQUAL }, - { "_ip6_cmp", "1:2:3:4:5:6:7:8", "1:1:3:4:5:6:7:8", SFIP_GREATER }, - { "_ip6_cmp", "1:2:3:4:5:6:7:8", "1:2:4:4:5:6:7:8", SFIP_LESSER }, - { "_ip6_cmp", "1:2:3:4:5:6:7:8", "1:2:3:4:5:5:7:8", SFIP_GREATER }, - { "_ip6_cmp", "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:8:8", SFIP_LESSER }, + // v6<->v6 Comparisons + { "sfip_compare", "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8", SFIP_EQUAL }, + { "sfip_compare", "1:2:3:4:5:6:7:8", "1:1:3:4:5:6:7:8", SFIP_GREATER }, + { "sfip_compare", "1:2:3:4:5:6:7:8", "1:2:4:4:5:6:7:8", SFIP_LESSER }, + { "sfip_compare", "1:2:3:4:5:6:7:8", "1:2:3:4:5:5:7:8", SFIP_GREATER }, + { "sfip_compare", "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:8:8", SFIP_LESSER }, { "sfip_compare", "1.2.3.4", "1.2.3.4", SFIP_EQUAL }, { "sfip_compare", "255.255.255.255", "192.168.0.1", SFIP_GREATER }, @@ -160,15 +160,8 @@ static FuncTest ftests[] = { "sfip_compare_unset", "1.2.3.4", "1.2.3.4", SFIP_EQUAL }, { "sfip_compare_unset", "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8", SFIP_EQUAL }, { "sfip_compare_unset", "1.2.3.4", "0.0.0.0", SFIP_FAILURE }, - { "sfip_compare_unset", "1:2:3:4:5:6:7:8", "::", SFIP_FAILURE }, - - { "sfip_fast_lt4", "1.2.3.4", "1.2.3.4", SFIP_FAILURE }, - { "sfip_fast_lt4", "1.2.3.4", "1.2.3.5", SFIP_SUCCESS }, - { "sfip_fast_lt4", "1.2.3.5", "1.2.3.4", SFIP_FAILURE }, - { "sfip_fast_gt4", "1.2.3.4", "1.2.3.4", SFIP_FAILURE }, - { "sfip_fast_gt4", "1.2.3.4", "1.2.3.5", SFIP_FAILURE }, - { "sfip_fast_gt4", "1.2.3.5", "1.2.3.4", SFIP_SUCCESS }, + { "sfip_compare_unset", "1:2:3:4:5:6:7:8", "::", SFIP_FAILURE }, { "sfip_fast_eq4", "1.2.3.4", "1.2.3.4", SFIP_SUCCESS }, { "sfip_fast_eq4", "1.2.3.4", "1.2.3.5", SFIP_FAILURE }, @@ -214,8 +207,17 @@ static FuncTest ftests[] = { "sfip_contains", "1001:db8:85a3::/28", "1001:db0::", SFIP_CONTAINS }, { "sfip_contains", "1001:db8:85a3::/29", "1001:db0::", SFIP_NOT_CONTAINS }, + { "sfip_contains", "ffee:ddcc:bbaa:9988:7766:5544:3322:1101", + "ffee:ddcc:bbaa:9988:7766:5544:3322:1102", SFIP_NOT_CONTAINS }, + { "sfip_contains", "ffee:ddcc:bbaa:9988:7766:5544:3322:1101/96", + "ffee:ddcc:bbaa:9988:7766:5544:3322:1102", SFIP_CONTAINS }, + { "sfip_contains", "ffee:ddcc:bbaa:9988:7766:5544:3322:1101/97", + "ffee:ddcc:bbaa:9988:7766:5544:3322:1102", SFIP_CONTAINS }, + { "sfip_contains", "ffee:ddcc:bbaa:9988:7766:5544:3322:1101/97", + "ffee:ddcc:bbaa:9988:7766:5544:b322:1102", SFIP_NOT_CONTAINS }, + { "sfip_contains", "255.255.255.255", - "2001:0db8:0000:0000:0000:0000:1428:57ab", SFIP_ARG_ERR }, + "2001:0db8:0000:0000:0000:0000:1428:57ab", SFIP_NOT_CONTAINS }, { "sfip_obfuscate", "::", "0000:0000:0000:0000:0000:0000:0000:0000", SFIP_EQUAL }, @@ -234,105 +236,87 @@ static FuncTest ftests[] = static int RunFunc(const char* func, const char* arg1, const char* arg2) { - sfip_t ip1, ip2; - sfip_clear(ip1); - sfip_clear(ip2); + SfCidr cidr1, cidr2; + const SfIp* ip1, * ip2; int result = SFIP_FAILURE; - if ( arg1 ) - sfip_pton(arg1, &ip1); - if ( arg2 ) - sfip_pton(arg2, &ip2); + cidr1.clear(); + if (arg1) + cidr1.set(arg1); + ip1 = cidr1.get_addr(); + + cidr2.clear(); + if (arg2) + cidr2.set(arg2); + ip2 = cidr2.get_addr(); if ( !strcmp(func, "sfip_pton") ) { - char buf1[INET6_ADDRSTRLEN]; - char buf2[INET6_ADDRSTRLEN]; - - sfip_ntop(&ip1, buf1, sizeof(buf1)); - sfip_ntop(&ip2, buf2, sizeof(buf2)); + char buf[INET6_ADDRSTRLEN]; - result = strcmp(buf1, buf2) ? SFIP_FAILURE : SFIP_SUCCESS; - } - else if ( !strcmp(func, "sfip_size") and arg2 ) - { - result = sfip_size(&ip1); - result = (result == atoi(arg2)) ? SFIP_SUCCESS : SFIP_FAILURE; + sfip_ntop(ip1, buf, sizeof(buf)); + if (arg2) + result = strcmp(buf, arg2) ? SFIP_FAILURE : SFIP_SUCCESS; } else if ( !strcmp(func, "sfip_contains") ) { - result = sfip_contains(&ip1, &ip2); + result = cidr1.contains(ip2); } else if ( !strcmp(func, "sfip_is_set") ) { - result = !sfip_is_set(&ip1); + result = !ip1->is_set(); } else if ( !strcmp(func, "sfip_is_loopback") ) { - result = !sfip_is_loopback(&ip1); + result = !ip1->is_loopback(); } else if ( !strcmp(func, "sfip_ismapped") ) { - result = !sfip_ismapped(&ip1); - } - else if ( !strcmp(func, "_ip6_cmp") ) - { - result = _ip6_cmp(&ip1, &ip2); + result = !ip1->is_mapped(); } else if ( !strcmp(func, "sfip_compare") ) { - result = sfip_compare(&ip1, &ip2); + result = ip1->compare(*ip2); } else if ( !strcmp(func, "sfip_compare_unset") ) { - result = sfip_compare_unset(&ip1, &ip2); - } - else if ( !strcmp(func, "sfip_fast_lt4") ) - { - result = !sfip_fast_lt4(&ip1, &ip2); - } - else if ( !strcmp(func, "sfip_fast_gt4") ) - { - result = !sfip_fast_gt4(&ip1, &ip2); + result = ip1->compare(*ip2, false); } else if ( !strcmp(func, "sfip_fast_eq4") ) { - result = !sfip_fast_eq4(&ip1, &ip2); + result = !ip1->fast_eq4(*ip2); } else if ( !strcmp(func, "sfip_fast_lt6") ) { - result = !sfip_fast_lt6(&ip1, &ip2); + result = !ip1->fast_lt6(*ip2); } else if ( !strcmp(func, "sfip_fast_gt6") ) { - result = !sfip_fast_gt6(&ip1, &ip2); + result = !ip1->fast_gt6(*ip2); } else if ( !strcmp(func, "sfip_fast_eq6") ) { - result = !sfip_fast_eq6(&ip1, &ip2); + result = !ip1->fast_eq6(*ip2); } else if ( !strcmp(func, "sfip_fast_cont4") ) { - result = !sfip_fast_cont4(&ip1, &ip2); + result = !cidr1.fast_cont4(*ip2); } else if ( !strcmp(func, "sfip_fast_cont6") ) { - result = !sfip_fast_cont6(&ip1, &ip2); + result = !cidr1.fast_cont6(*ip2); } else if ( !strcmp(func, "sfip_obfuscate") ) { - sfip_t ip; - if ( ip1.family == AF_INET ) - { - sfip_pton("4.3.2.1", &ip); - } + SfIp ip; + if ( ip1->get_family() == AF_INET ) + ip.set("4.3.2.1"); else - { - sfip_pton("8:7:6:5:4:3:2:1", &ip); - } - sfip_obfuscate(&ip1, &ip); - result = sfip_compare(&ip, &ip2); + ip.set("8:7:6:5:4:3:2:1"); + ip.obfuscate(&cidr1); + result = ip.compare(*ip2); } + return result; } @@ -367,74 +351,14 @@ static int FuncCheck(int i) return result == f->expected; } -static int AllocCheck(int i) -{ - FuncTest* f = ftests + i; - SFIP_RET status; - sfip_t* pip1, * pip2; - - pip1 = sfip_alloc(f->arg1, &status); - if ( !pip1 || status != SFIP_SUCCESS ) - return 0; - - if ( f->arg2 ) - { - pip2 = sfip_alloc(f->arg2, &status); - } - else - { - unsigned int i = 0xffffffff; - pip2 = sfip_alloc_raw(&i, AF_INET, &status); - } - if ( !pip2 || status != SFIP_SUCCESS ) - return 0; - - sfip_free(pip1); - sfip_free(pip2); - - return 1; -} - -static int RawCheck(int i) -{ - SFIP_RET status; - uint8_t addr[16]; - const char* s, * exp; - size_t j; - sfip_t* pip; - - for ( j = 0; j < sizeof(addr); j++ ) - // avoid leading zero confusion - addr[j] = j | (j % 2 ? 0x00 : 0x80); - - if ( i ) - { - pip = sfip_alloc_raw(addr, AF_INET6, &status); - exp = "8001:8203:8405:8607:8809:8a0b:8c0d:8e0f"; - } - else - { - pip = sfip_alloc_raw(addr, AF_INET, &status); - exp = "128.1.130.3"; - } - if ( status != SFIP_SUCCESS ) - return 0; - - s = sfip_to_str(pip); - sfip_free(pip); - - return !strcasecmp(s, exp); -} - static int SetCheck(int i) { FuncTest* f = ftests + i; - SFIP_RET status; - sfip_t ip1, ip2; + SfIpRet status; + SfIp ip1, ip2; - sfip_pton(f->arg1, &ip1); - status = sfip_set_raw(&ip2, ip1.ip8, ip1.family); - sfip_set_bits(&ip2, sfip_bits(&ip1)); + ip1.set(f->arg1); + status = ip2.set(ip1.get_ptr(), ip1.get_family()); return (status == SFIP_SUCCESS) && !memcmp(&ip1, &ip2, sizeof(ip1)); } @@ -442,13 +366,12 @@ static int SetCheck(int i) static int CopyCheck(int i) { FuncTest* f = ftests + i; - SFIP_RET status; - sfip_t ip1, ip2; + SfIp ip1, ip2; - sfip_pton(f->arg1, &ip1); - status = sfip_set_ip(&ip2, &ip1); + ip1.set(f->arg1); + ip2.set(ip1); - return (status == SFIP_SUCCESS) && !memcmp(&ip1, &ip2, sizeof(ip1)); + return !memcmp(&ip1, &ip2, sizeof(ip1)); } //--------------------------------------------------------------- @@ -470,16 +393,3 @@ TEST_CASE("sfip copy", "[sfip]") for ( unsigned i = 0; i < NUM_TESTS; ++i ) CHECK(CopyCheck(i) == 1); } - -TEST_CASE("sfip alloc", "[sfip]") -{ - for ( unsigned i = 0; i < NUM_TESTS; ++i ) - CHECK(AllocCheck(i) == 1); -} - -TEST_CASE("sfip raw", "[sfip]") -{ - for ( unsigned i = 0; i < 2; ++i ) - CHECK(RawCheck(i) == 1); -} - diff --git a/src/sfrt/dev_notes.txt b/src/sfrt/dev_notes.txt index 88b3dcc90..0af0ca1ca 100644 --- a/src/sfrt/dev_notes.txt +++ b/src/sfrt/dev_notes.txt @@ -2,10 +2,8 @@ SFRT implements two different routing table lookup methods that have been adapted to return a void pointers. Any generic information may be associated with a given IP or 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 for testing purposes as the -current implementation does not allow for fast, dynamic inserts. +As of this writing, the method used is a multibit-trie method similar to Gupta +et-al.'s DIR-n-m. The intended use is to associate large IP blocks with specific information. diff --git a/src/sfrt/sfrt.cc b/src/sfrt/sfrt.cc index a2b8172f6..70981fcbe 100644 --- a/src/sfrt/sfrt.cc +++ b/src/sfrt/sfrt.cc @@ -83,7 +83,7 @@ #include "config.h" #endif -#include "main/snort_types.h" +#include "sfip/sf_cidr.h" #include "utils/util.h" const char* rt_error_messages[] = @@ -94,12 +94,6 @@ const char* rt_error_messages[] = "Dir Insert Failure", "Dir Lookup Failure", "Memory Allocation Failure" -#ifdef SUPPORT_LCTRIE - , - "LC Trie Compile Failure", - "LC Trie Insert Failure", - "LC Trie Lookup Failure" -#endif }; static inline int allocateTableIndex(table_t* table); @@ -117,18 +111,10 @@ table_t* sfrt_new(char table_type, char ip_type, long data_size, uint32_t mem_ca /* If this limit is exceeded, there will be no way to distinguish * between pointers and indeces into the data table. Only * applies to DIR-n-m. */ -#ifdef SUPPORT_LCTRIE -#if SIZEOF_LONG_INT == 8 - if (data_size >= 0x800000000000000 && table_type == LCT) -#else - if (data_size >= 0x8000000 && table_type != LCT) -#endif -#else /* SUPPORT_LCTRIE */ #if SIZEOF_LONG_INT == 8 if (data_size >= 0x800000000000000) #else if (data_size >= 0x8000000) -#endif #endif { snort_free(table); @@ -157,24 +143,6 @@ table_t* sfrt_new(char table_type, char ip_type, long data_size, uint32_t mem_ca switch (table_type) { -#ifdef SUPPORT_LCTRIE - /* Setup LC-trie table */ - case LCT: - /* LC trie is presently not allowed */ - table->insert = sfrt_lct_insert; - table->lookup = sfrt_lct_lookup; - table->free = sfrt_lct_free; - table->usage = sfrt_lct_usage; - table->print = NULL; - table->remove = NULL; - - table->rt = sfrt_lct_new(data_size); - snort_free(table->data); - snort_free(table); - return NULL; - - break; -#endif /* Setup DIR-n-m table */ case DIR_24_8: case DIR_16x2: @@ -304,41 +272,36 @@ void sfrt_free(table_t* table) } /* Perform a lookup on value contained in "ip" */ -GENERIC sfrt_lookup(sfip_t* ip, table_t* table) +GENERIC sfrt_lookup(const SfIp* ip, table_t* table) { tuple_t tuple; - void* rt = NULL; + const uint32_t* addr; + int numAddrDwords; + void* rt ; - if (!ip) - { + if (!ip || !table || !table->lookup) return NULL; - } - if (!table || !table->lookup) - { - return NULL; - } - - if (ip->family == AF_INET) + if (ip->is_ip4()) { + addr = ip->get_ip4_ptr(); + numAddrDwords = 1; rt = table->rt; } - else if (ip->family == AF_INET6) + else { + addr = ip->get_ip6_ptr(); + numAddrDwords = 4; rt = table->rt6; } if (!rt) - { return NULL; - } - tuple = table->lookup(ip, rt); + tuple = table->lookup(addr, numAddrDwords, rt); if (tuple.index >= table->max_size) - { return NULL; - } return table->data[tuple.index]; } @@ -485,22 +448,32 @@ void sfrt_cleanup(table_t* table, sfrt_iterator_callback cleanup_func) } } -GENERIC sfrt_search(sfip_t* ip, unsigned char len, table_t* table) +GENERIC sfrt_search(const SfIp* ip, unsigned char len, table_t* table) { + const uint32_t* addr; + int numAddrDwords; tuple_t tuple; - void* rt = NULL; + void* rt; if ((ip == NULL) || (table == NULL) || (len == 0)) return NULL; - if (ip->family == AF_INET) + if (ip->is_ip4()) { + addr = ip->get_ip4_ptr(); + numAddrDwords = 1; rt = table->rt; } - else if (ip->family == AF_INET6) + else if (ip->is_ip6()) { + addr = ip->get_ip6_ptr(); + numAddrDwords = 4; rt = table->rt6; } + else + return NULL; + + /* FIXIT-M - Is is true that we don't support v6 yet? */ /* IPv6 not yet supported */ if (table->ip_type == IPv6) return NULL; @@ -511,7 +484,7 @@ GENERIC sfrt_search(sfip_t* ip, unsigned char len, table_t* table) return NULL; } - tuple = table->lookup(ip, rt); + tuple = table->lookup(addr, numAddrDwords, rt); if (tuple.length != len) return NULL; @@ -519,18 +492,20 @@ GENERIC sfrt_search(sfip_t* ip, unsigned char len, table_t* table) return table->data[tuple.index]; } -/* Insert "ip", of length "len", into "table", and have it point to "ptr" - Insert "ip", of length "len", into "table", and have it point to "ptr" */ -int sfrt_insert(sfip_t* ip, unsigned char len, GENERIC ptr, +/* 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 = NULL; + void* rt; - if (!ip) + if (!cidr) { return RT_INSERT_FAILURE; } @@ -551,39 +526,29 @@ int sfrt_insert(sfip_t* ip, unsigned char len, GENERIC ptr, /* Check if we can reuse an existing data table entry by * seeing if there is an existing entry with the same length. */ - /* Only perform this if the table is not an LC-trie */ -#ifdef SUPPORT_LCTRIE - if (table->table_type != LCT) - { -#endif - - if (ip->family == AF_INET) - { + 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->family == AF_INET6) + else if (ip->is_ip6()) { + addr = ip->get_ip6_ptr(); + numAddrDwords = 4; rt = table->rt6; } - if (!rt) - { + else return RT_INSERT_FAILURE; - } - tuple = table->lookup(ip, rt); + tuple = table->lookup(addr, numAddrDwords, rt); -#ifdef SUPPORT_LCTRIE -} - -#endif - -#ifdef SUPPORT_LCTRIE - if (table->table_type == LCT || tuple.length != len) - { -#else if (tuple.length != len) { -#endif if ( table->num_ent >= table->max_size) { return RT_POLICY_TABLE_EXCEEDED; @@ -600,7 +565,7 @@ int sfrt_insert(sfip_t* ip, unsigned char len, GENERIC ptr, /* The actual value that is looked-up is an index * into the data table. */ - res = table->insert(ip, len, index, behavior, rt); + res = table->insert(addr, numAddrDwords, len, index, behavior, rt); if ((res == RT_SUCCESS) && newIndex) { @@ -666,13 +631,16 @@ uint32_t sfrt_usage(table_t* table) * 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(sfip_t* ip, unsigned char len, GENERIC* ptr, +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 = NULL; + void* rt; - if (!ip) + if (!cidr) { return RT_REMOVE_FAILURE; } @@ -681,10 +649,7 @@ int sfrt_remove(sfip_t* ip, unsigned char len, GENERIC* ptr, return RT_REMOVE_FAILURE; if (!table || !table->data || !table->remove || !table->lookup ) - { - // remove operation will fail for LCT since this operation is not implemented return RT_REMOVE_FAILURE; - } if ( (table->ip_type == IPv4 && len > 32) || (table->ip_type == IPv6 && len > 128) ) @@ -692,32 +657,28 @@ int sfrt_remove(sfip_t* ip, unsigned char len, GENERIC* ptr, return RT_REMOVE_FAILURE; } -#ifdef SUPPORT_LCTRIE - if (table->table_type != LCT) - { -#endif - - if (ip->family == AF_INET) + 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->family == AF_INET6) + else if (ip->is_ip6()) { + addr = ip->get_ip6_ptr(); + numAddrDwords = 4; rt = table->rt6; } - if (!rt) - { + else return RT_REMOVE_FAILURE; - } - -#ifdef SUPPORT_LCTRIE -} - -#endif /* The actual value that is looked-up is an index * into the data table. */ - index = table->remove(ip, len, behavior, rt); + index = table->remove(addr, numAddrDwords, len, behavior, rt); /* Remove value into policy table. See TBD in function header*/ if (index) diff --git a/src/sfrt/sfrt.h b/src/sfrt/sfrt.h index a2b09c730..011c51085 100644 --- a/src/sfrt/sfrt.h +++ b/src/sfrt/sfrt.h @@ -23,18 +23,11 @@ #ifndef SFRT_H #define SFRT_H -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include -#include +#include -#include "main/snort_debug.h" +#include "sfip/sf_ip.h" #include "sfrt/sfrt_trie.h" -#include "sfip/sfip_t.h" -typedef sfip_t* IP; typedef void* GENERIC; /* To be replaced with a pointer to a policy */ struct tuple_t { @@ -43,16 +36,9 @@ struct tuple_t }; #include "sfrt/sfrt_dir.h" -//#define SUPPORT_LCTRIE -#ifdef SUPPORT_LCTRIE -#include "sfrt/sfrt_lctrie.h" -#endif enum types { -#ifdef SUPPORT_LCTRIE - LCT, -#endif DIR_24_8, DIR_16x2, DIR_16_8x2, @@ -76,11 +62,6 @@ enum return_codes DIR_INSERT_FAILURE, DIR_LOOKUP_FAILURE, MEM_ALLOC_FAILURE, -#ifdef SUPPORT_LCTRIE - LCT_COMPILE_FAILURE, - LCT_INSERT_FAILURE, - LCT_LOOKUP_FAILURE, -#endif RT_REMOVE_FAILURE }; @@ -110,20 +91,20 @@ typedef struct void* rt; /* Actual "routing" table */ void* rt6; /* Actual "routing" table */ - tuple_t (* lookup)(IP ip, GENERIC tbl); - int (* insert)(IP ip, int len, word index, int behavior, GENERIC tbl); + tuple_t (* lookup)(const uint32_t* addr, int numAddrDwords, GENERIC tbl); + int (* insert)(const uint32_t* addr, int numAddrDwords, int len, word index, int behavior, GENERIC tbl); void (* free)(GENERIC tbl); uint32_t (* usage)(GENERIC tbl); void (* print)(GENERIC tbl); - word (* remove)(IP ip, int len, int behavior, GENERIC tbl); + word (* remove)(const uint32_t* addr, int numAddrDwords, int len, int behavior, GENERIC tbl); } table_t; /*******************************************************************/ /* 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* table); -GENERIC sfrt_lookup(sfip_t* ip, table_t* table); -GENERIC sfrt_search(sfip_t* ip, unsigned char len, table_t* table); +GENERIC sfrt_lookup(const SfIp* ip, table_t* table); +GENERIC sfrt_search(const SfIp* ip, unsigned char len, table_t* table); typedef void (* sfrt_iterator_callback)(void*); struct SnortConfig; typedef void (* sfrt_sc_iterator_callback)(SnortConfig*, void*); @@ -138,77 +119,12 @@ int sfrt_iterate2_with_snort_config(SnortConfig* sc, table_t* table, sfrt_sc_ite userfunc); void sfrt_cleanup(table_t* table, sfrt_iterator_callback userfunc); void sfrt_cleanup2(table_t*, sfrt_iterator_callback2, void*); -int sfrt_insert(sfip_t* ip, unsigned char len, GENERIC ptr, +int sfrt_insert(SfCidr* cidr, unsigned char len, GENERIC ptr, int behavior, table_t* table); -int sfrt_remove(sfip_t* ip, unsigned char len, GENERIC* ptr, +int sfrt_remove(SfCidr* cidr, unsigned char len, GENERIC* ptr, int behavior, table_t* table); uint32_t sfrt_usage(table_t* table); void sfrt_print(table_t* table); uint32_t sfrt_num_entries(table_t* table); -/* Perform a lookup on value contained in "ip" - * For performance reason, we use this simplified version instead of sfrt_lookup - * Note: this only applied to table setting: DIR_8x16 (DIR_16_8_4x2 for IPV4), DIR_8x4*/ -inline GENERIC sfrt_dir8x_lookup(void* adr, table_t* table) -{ - dir_sub_table_t* subtable; - int i; - sfip_t* ip; - void* rt = NULL; - int index; - - ip = (sfip_t*)adr; - if (ip->family == AF_INET) - { - rt = table->rt; - subtable = ((dir_table_t*)rt)->sub_table; - /* 16 bits*/ - index = ntohs(ip->ip16[0]); - if ( !subtable->entries[index] || subtable->lengths[index] ) - { - return table->data[subtable->entries[index]]; - } - subtable = (dir_sub_table_t*)subtable->entries[index]; - - /* 8 bits*/ - index = ip->ip8[2]; - if ( !subtable->entries[index] || subtable->lengths[index] ) - { - return table->data[subtable->entries[index]]; - } - subtable = (dir_sub_table_t*)subtable->entries[index]; - - /* 4 bits */ - index = ip->ip8[3] >> 4; - if ( !subtable->entries[index] || subtable->lengths[index] ) - { - return table->data[subtable->entries[index]]; - } - subtable = (dir_sub_table_t*)subtable->entries[index]; - - /* 4 bits */ - index = ip->ip8[3] & 0xF; - if ( !subtable->entries[index] || subtable->lengths[index] ) - { - return table->data[subtable->entries[index]]; - } - } - else if (ip->family == AF_INET6) - { - rt = table->rt6; - subtable = ((dir_table_t*)rt)->sub_table; - for (i = 0; i < 16; i++) - { - index = ip->ip8[i]; - if ( !subtable->entries[index] || subtable->lengths[index] ) - { - return table->data[subtable->entries[index]]; - } - subtable = (dir_sub_table_t*)subtable->entries[index]; - } - } - return NULL; -} - #endif - diff --git a/src/sfrt/sfrt_dir.cc b/src/sfrt/sfrt_dir.cc index 4980870d4..6bbfd5360 100644 --- a/src/sfrt/sfrt_dir.cc +++ b/src/sfrt/sfrt_dir.cc @@ -26,23 +26,20 @@ * 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 /* For variadic */ -#include -#include /* For memset */ +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif -#include "main/snort_types.h" #include "utils/util.h" typedef struct { - IP ip; + const uint32_t* addr; int bits; } IPLOOKUP; @@ -374,35 +371,24 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, GENERIC ptr, { uint32_t local_index, i; /* need to handle bits usage across multiple 32bit vals within IPv6. */ - if (ip->ip->family == AF_INET) + if (ip->bits < 32) { i=0; } - else if (ip->ip->family == AF_INET6) + else if (ip->bits < 64) { - if (ip->bits < 32 ) - { - i=0; - } - else if (ip->bits < 64) - { - i=1; - } - else if (ip->bits < 96) - { - i=2; - } - else - { - i=3; - } + i=1; + } + else if (ip->bits < 96) + { + i=2; } else { - return RT_INSERT_FAILURE; + i=3; } - local_index = ip->ip->ip32[i] << (ip->bits %32); - index = local_index >> (sizeof(local_index)*8 - sub_table->width); + 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 */ @@ -477,18 +463,14 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, GENERIC ptr, return RT_SUCCESS; } -/* Insert entry into DIR-n-m tables - * @param ip IP address structure - * @param len Number of bits of the IP used for lookup - * @param ptr Information to be associated with this IP range - * @param master_table The table that describes all, returned by dir_new */ -int sfrt_dir_insert(IP ip, int len, word data_index, +/* 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; - sfip_t h_ip; + uint32_t h_addr[4]; IPLOOKUP iplu; - iplu.ip = &h_ip; + iplu.addr = h_addr; iplu.bits = 0; /* Validate arguments */ @@ -497,25 +479,30 @@ int sfrt_dir_insert(IP ip, int len, word data_index, return DIR_INSERT_FAILURE; } - h_ip.family = ip->family; - h_ip.ip32[0] = ntohl(ip->ip32[0]); - if (ip->family != AF_INET) + h_addr[0] = ntohl(addr[0]); + if (len > 96) { - if (len > 96) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - h_ip.ip32[2] = ntohl(ip->ip32[2]); - h_ip.ip32[3] = ntohl(ip->ip32[3]); - } - else if (len > 64) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - h_ip.ip32[2] = ntohl(ip->ip32[2]); - } - else if (len > 32) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - } + 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 */ @@ -531,36 +518,24 @@ static tuple_t _dir_sub_lookup(IPLOOKUP* ip, dir_sub_table_t* table) { uint32_t local_index, i; /* need to handle bits usage across multiple 32bit vals within IPv6. */ - if (ip->ip->family == AF_INET) + if (ip->bits < 32 ) { i=0; } - else if (ip->ip->family == AF_INET6) + else if (ip->bits < 64) { - if (ip->bits < 32 ) - { - i=0; - } - else if (ip->bits < 64) - { - i=1; - } - else if (ip->bits < 96) - { - i=2; - } - else - { - i=3; - } + i=1; + } + else if (ip->bits < 96) + { + i=2; } else { - tuple_t ret = { 0, 0 }; - return ret; + i=3; } - local_index = ip->ip->ip32[i] << (ip->bits %32); - index = local_index >> (sizeof(local_index)*8 - table->width); + local_index = ip->addr[i] << (ip->bits % 32); + index = local_index >> (sizeof(local_index) * 8 - table->width); } if ( !table->entries[index] || table->lengths[index] ) @@ -577,29 +552,24 @@ static tuple_t _dir_sub_lookup(IPLOOKUP* ip, dir_sub_table_t* table) } /* Lookup information associated with the value "ip" */ -tuple_t sfrt_dir_lookup(IP ip, void* tbl) +tuple_t sfrt_dir_lookup(const uint32_t* addr, int numAddrDwords, void* tbl) { dir_table_t* root = (dir_table_t*)tbl; - sfip_t h_ip; + uint32_t h_addr[4]; + int i; IPLOOKUP iplu; - iplu.ip = &h_ip; + iplu.addr = h_addr; iplu.bits = 0; - if (!root || !root->sub_table) + if (!root || !root->sub_table || numAddrDwords < 1) { tuple_t ret = { 0, 0 }; return ret; } - h_ip.family = ip->family; - h_ip.ip32[0] = ntohl(ip->ip32[0]); - if (ip->family != AF_INET) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - h_ip.ip32[2] = ntohl(ip->ip32[2]); - h_ip.ip32[3] = ntohl(ip->ip32[3]); - } + for (i= 0 ; i < numAddrDwords; i++) + h_addr[i] = ntohl(addr[i]); return _dir_sub_lookup(&iplu, root->sub_table); } @@ -680,35 +650,24 @@ static int _dir_sub_remove(IPLOOKUP* ip, int length, int cur_len, { uint32_t local_index, i; /* need to handle bits usage across multiple 32bit vals within IPv6. */ - if (ip->ip->family == AF_INET) + if (ip->bits < 32) { i=0; } - else if (ip->ip->family == AF_INET6) + else if (ip->bits < 64) { - if (ip->bits < 32 ) - { - i=0; - } - else if (ip->bits < 64) - { - i=1; - } - else if (ip->bits < 96) - { - i=2; - } - else - { - i=3; - } + i=1; + } + else if (ip->bits < 96) + { + i=2; } else { - return 0; + i=3; } - local_index = ip->ip->ip32[i] << (ip->bits %32); - index = local_index >> (sizeof(local_index)*8 - sub_table->width); + 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 */ @@ -767,19 +726,15 @@ static int _dir_sub_remove(IPLOOKUP* ip, int length, int cur_len, } /* Remove entry into DIR-n-m tables - * @param ip IP address structure - * @param len Number of bits of the IP used for lookup - * @param behavior RT_FAVOR_SPECIFIC or RT_FAVOR_TIME - * @param table The table that describes all, returned by dir_new * @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(IP ip, int len, int behavior, void* table) +word sfrt_dir_remove(const uint32_t* addr, int /* numAddrDwords */, int len, int behavior, void* table) { dir_table_t* root = (dir_table_t*)table; - sfip_t h_ip; + uint32_t h_addr[4]; IPLOOKUP iplu; - iplu.ip = &h_ip; + iplu.addr = h_addr; iplu.bits = 0; /* Validate arguments */ @@ -788,34 +743,30 @@ word sfrt_dir_remove(IP ip, int len, int behavior, void* table) return 0; } - h_ip.family = ip->family; - h_ip.ip32[0] = ntohl(ip->ip32[0]); - if (ip->family != AF_INET) + h_addr[0] = ntohl(addr[0]); + if (len > 96) { - if (len > 96) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - h_ip.ip32[2] = ntohl(ip->ip32[2]); - h_ip.ip32[3] = ntohl(ip->ip32[3]); - } - else if (len > 64) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - h_ip.ip32[2] = ntohl(ip->ip32[2]); - h_ip.ip32[3] = 0; - } - else if (len > 32) - { - h_ip.ip32[1] = ntohl(ip->ip32[1]); - h_ip.ip32[2] = 0; - h_ip.ip32[3] = 0; - } - else - { - h_ip.ip32[1] = 0; - h_ip.ip32[2] = 0; - h_ip.ip32[3] = 0; - } + 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 */ diff --git a/src/sfrt/sfrt_dir.h b/src/sfrt/sfrt_dir.h index 8a9419bd6..38eb3363f 100644 --- a/src/sfrt/sfrt_dir.h +++ b/src/sfrt/sfrt_dir.h @@ -75,12 +75,12 @@ typedef struct 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(IP ip, void* table); -int sfrt_dir_insert(IP ip, int len, word data_index, +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(IP ip, int len, int behavior, void* table); +word sfrt_dir_remove(const uint32_t* addr, int numAddrDwords, int len, int behavior, void* table); #endif /* SFRT_DIR_H */ diff --git a/src/sfrt/sfrt_flat.cc b/src/sfrt/sfrt_flat.cc index 55b18fab8..98442da14 100644 --- a/src/sfrt/sfrt_flat.cc +++ b/src/sfrt/sfrt_flat.cc @@ -24,8 +24,7 @@ #include "config.h" #endif -#include "main/snort_types.h" -#include "main/snort_debug.h" +#include "sfip/sf_cidr.h" #define MINIMUM_TABLE_MEMORY (768 * 1024) @@ -211,15 +210,16 @@ void sfrt_flat_free(TABLE_PTR table_ptr) } /* Perform a lookup on value contained in "ip" */ -GENERIC sfrt_flat_lookup(void* adr, table_flat_t* table) +GENERIC sfrt_flat_lookup(const SfIp* ip, table_flat_t* table) { tuple_flat_t tuple; + const uint32_t* addr; + int numAddrDwords; INFO* data; - sfip_t* ip; TABLE_PTR rt = 0; uint8_t* base; - if (!adr) + if (!ip) { return NULL; } @@ -229,22 +229,22 @@ GENERIC sfrt_flat_lookup(void* adr, table_flat_t* table) return NULL; } - ip = (sfip_t*)adr; - if (ip->family == AF_INET) + if (ip->is_ip4()) { + addr = ip->get_ip4_ptr(); + numAddrDwords = 1; rt = table->rt; } - else if (ip->family == AF_INET6) + else if (ip->is_ip6()) { + addr = ip->get_ip6_ptr(); + numAddrDwords = 4; rt = table->rt6; } - - if (!rt) - { + else return NULL; - } - tuple = sfrt_dir_flat_lookup(ip, rt); + tuple = sfrt_dir_flat_lookup(addr, numAddrDwords, rt); if (tuple.index >= table->num_ent) { @@ -258,21 +258,22 @@ GENERIC sfrt_flat_lookup(void* adr, table_flat_t* table) return NULL; } -/* Insert "ip", of length "len", into "table", and have it point to "ptr" - Insert "ip", of length "len", into "table", and have it point to "ptr" */ -int sfrt_flat_insert(void* adr, unsigned char len, INFO ptr, +/* Insert "ip", of length "len", into "table", and have it point to "ptr" */ +int sfrt_flat_insert(SfCidr* cidr, unsigned char len, INFO ptr, int behavior, table_flat_t* table, updateEntryInfoFunc updateEntry) { + const SfIp* ip; int index; int res = RT_SUCCESS; INFO* data; - sfip_t* ip; tuple_flat_t tuple; - TABLE_PTR rt = 0; + const uint32_t* addr; + int numAddrDwords; + TABLE_PTR rt; uint8_t* base; int64_t bytesAllocated; - if (!adr ) + if (!cidr) { return RT_INSERT_FAILURE; } @@ -285,28 +286,31 @@ int sfrt_flat_insert(void* adr, unsigned char len, INFO ptr, return RT_INSERT_FAILURE; } - if ( (table->ip_type == IPv4 && len > 32) || - (table->ip_type == IPv6 && len > 128) ) + if (len > 128) { return RT_INSERT_FAILURE; } - ip = (sfip_t*)adr; - - if (ip->family == AF_INET) + 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->family == AF_INET6) + else if (ip->is_ip6()) { + addr = ip->get_ip6_ptr(); + numAddrDwords = 4; rt = table->rt6; } - if (!rt) - { + else return RT_INSERT_FAILURE; - } - tuple = sfrt_dir_flat_lookup(ip, table->rt); + tuple = sfrt_dir_flat_lookup(addr, numAddrDwords, table->rt); base = (uint8_t*)segment_basePtr(); data = (INFO*)(&base[table->data]); @@ -341,7 +345,7 @@ int sfrt_flat_insert(void* adr, unsigned char len, INFO ptr, /* The actual value that is looked-up is an index * into the data table. */ - res = sfrt_dir_flat_insert(ip, len, index, behavior, rt, updateEntry, data); + res = sfrt_dir_flat_insert(addr, numAddrDwords, len, index, behavior, rt, updateEntry, data); /* Check if we ran out of memory. If so, need to decrement * table->num_ent */ @@ -395,24 +399,22 @@ uint32_t sfrt_flat_usage(table_flat_t* table) /* Perform a lookup on value contained in "ip" * For performance reason, we use this simplified version instead of sfrt_lookup * Note: this only applied to table setting: DIR_8x16 (DIR_16_8_4x2 for IPV4), DIR_8x4*/ -GENERIC sfrt_flat_dir8x_lookup(void* adr, table_flat_t* table) +GENERIC sfrt_flat_dir8x_lookup(const SfIp* ip, table_flat_t* table) { dir_sub_table_flat_t* subtable; DIR_Entry* entry; uint8_t* base = (uint8_t*)table; int i; - sfip_t* ip; dir_table_flat_t* rt = NULL; int index; INFO* data = (INFO*)(&base[table->data]); - ip = (sfip_t*)adr; - if (ip->family == AF_INET) + if (ip->is_ip4()) { rt = (dir_table_flat_t*)(&base[table->rt]); subtable = (dir_sub_table_flat_t*)(&base[rt->sub_table]); /* 16 bits*/ - index = ntohs(ip->ip16[0]); + index = ntohs(((uint16_t*) ip->get_ip4_ptr())[0]); entry = (DIR_Entry*)(&base[subtable->entries]); if ( !entry[index].value || entry[index].length) { @@ -424,7 +426,7 @@ GENERIC sfrt_flat_dir8x_lookup(void* adr, table_flat_t* table) subtable = (dir_sub_table_flat_t*)(&base[entry[index].value]); /* 8 bits*/ - index = ip->ip8[2]; + index = ((uint8_t*) ip->get_ip4_ptr())[2]; entry = (DIR_Entry*)(&base[subtable->entries]); if ( !entry[index].value || entry[index].length) { @@ -436,7 +438,7 @@ GENERIC sfrt_flat_dir8x_lookup(void* adr, table_flat_t* table) subtable = (dir_sub_table_flat_t*)(&base[entry[index].value]); /* 4 bits */ - index = ip->ip8[3] >> 4; + index = ((uint8_t*) ip->get_ip4_ptr())[3] >> 4; entry = (DIR_Entry*)(&base[subtable->entries]); if ( !entry[index].value || entry[index].length) { @@ -448,7 +450,7 @@ GENERIC sfrt_flat_dir8x_lookup(void* adr, table_flat_t* table) subtable = (dir_sub_table_flat_t*)(&base[entry[index].value]); /* 4 bits */ - index = ip->ip8[3] & 0xF; + index = ((uint8_t*) ip->get_ip4_ptr())[3] & 0xF; entry = (DIR_Entry*)(&base[subtable->entries]); if ( !entry[index].value || entry[index].length) { @@ -458,13 +460,13 @@ GENERIC sfrt_flat_dir8x_lookup(void* adr, table_flat_t* table) return NULL; } } - else if (ip->family == AF_INET6) + else if (ip->is_ip6()) { rt = (dir_table_flat_t*)(&base[table->rt6]); subtable = (dir_sub_table_flat_t*)(&base[rt->sub_table]); for (i = 0; i < 16; i++) { - index = ip->ip8[i]; + index = ((uint8_t*) ip->get_ip6_ptr())[i]; entry = (DIR_Entry*)(&base[subtable->entries]); if ( !entry[index].value || entry[index].length) { diff --git a/src/sfrt/sfrt_flat.h b/src/sfrt/sfrt_flat.h index 0e1283b5b..7bca116c6 100644 --- a/src/sfrt/sfrt_flat.h +++ b/src/sfrt/sfrt_flat.h @@ -74,10 +74,10 @@ 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(void* adr, table_flat_t* table); -GENERIC sfrt_flat_dir8x_lookup(void* adr, table_flat_t* table); +GENERIC sfrt_flat_lookup(const SfIp* ip, table_flat_t* table); +GENERIC sfrt_flat_dir8x_lookup(const SfIp* ip, table_flat_t* table); -int sfrt_flat_insert(void* adr, unsigned char len, INFO ptr, int behavior, +int sfrt_flat_insert(SfCidr* cidr, unsigned char len, INFO ptr, int behavior, table_flat_t* table, updateEntryInfoFunc updateEntry); uint32_t sfrt_flat_usage(table_flat_t* table); uint32_t sfrt_flat_num_entries(table_flat_t* table); diff --git a/src/sfrt/sfrt_flat_dir.cc b/src/sfrt/sfrt_flat_dir.cc index 8b58a2a0f..8de888fed 100644 --- a/src/sfrt/sfrt_flat_dir.cc +++ b/src/sfrt/sfrt_flat_dir.cc @@ -18,17 +18,14 @@ //-------------------------------------------------------------------------- // 9/7/2011 - Initial implementation ... Hui Cao -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - #include "sfrt_flat.h" // FIXIT-L these includes are circular #include "sfrt_flat_dir.h" -#include /* For variadic */ -#include +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif -#include "main/snort_types.h" +#include #if SIZEOF_UNSIGNED_LONG_INT == 8 #define ARCH_WIDTH 64 @@ -38,7 +35,7 @@ typedef struct { - const sfip_t* ip; + const uint32_t* addr; int bits; } IPLOOKUP; @@ -373,34 +370,23 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, INFO ptr, { uint32_t local_index, i; /* need to handle bits usage across multiple 32bit vals within IPv6. */ - if (ip->ip->family == AF_INET) + if (ip->bits < 32) { i=0; } - else if (ip->ip->family == AF_INET6) + else if (ip->bits < 64) { - if (ip->bits < 32 ) - { - i=0; - } - else if (ip->bits < 64) - { - i=1; - } - else if (ip->bits < 96) - { - i=2; - } - else - { - i=3; - } + i=1; + } + else if (ip->bits < 96) + { + i=2; } else { - return RT_INSERT_FAILURE; + i=3; } - local_index = ip->ip->ip32[i] << (ip->bits %32); + local_index = ip->addr[i] << (ip->bits % 32); index = local_index >> (ARCH_WIDTH - sub_table->width); } @@ -483,20 +469,15 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, INFO ptr, return RT_SUCCESS; } -/* Insert entry into DIR-n-m tables - * @param ip IP address structure - * @param len Number of bits of the IP used for lookup - * @param ptr Information to be associated with this IP range - * @param master_table The table that describes all, returned by dir_new */ -int sfrt_dir_flat_insert(const sfip_t* ip, int len, word data_index, +/* Insert entry into DIR-n-m tables */ +int sfrt_dir_flat_insert(const uint32_t* addr, int /* numAddrDwords */, int len, word data_index, int behavior, TABLE_PTR table_ptr, updateEntryInfoFunc updateEntry, INFO* data) { dir_table_flat_t* root; - uint8_t* base; - + uint32_t h_addr[4]; IPLOOKUP iplu; - iplu.ip = ip; + iplu.addr = h_addr; iplu.bits = 0; base = (uint8_t*)segment_basePtr(); @@ -507,6 +488,32 @@ int sfrt_dir_flat_insert(const sfip_t* ip, int len, word data_index, 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, data_index, 0, behavior, root->sub_table, root, updateEntry, data); @@ -524,35 +531,23 @@ static tuple_flat_t _dir_sub_flat_lookup(IPLOOKUP* ip, TABLE_PTR table_ptr) { uint32_t local_index, i; /* need to handle bits usage across multiple 32bit vals within IPv6. */ - if (ip->ip->family == AF_INET) + if (ip->bits < 32) { i=0; } - else if (ip->ip->family == AF_INET6) + else if (ip->bits < 64) { - if (ip->bits < 32 ) - { - i=0; - } - else if (ip->bits < 64) - { - i=1; - } - else if (ip->bits < 96) - { - i=2; - } - else - { - i=3; - } + i=1; + } + else if (ip->bits < 96) + { + i=2; } else { - tuple_flat_t ret = { 0, 0 }; - return ret; + i=3; } - local_index = ip->ip->ip32[i] << (ip->bits %32); + local_index = ip->addr[i] << (ip->bits %32); index = local_index >> (ARCH_WIDTH - table->width); } entry = (DIR_Entry*)(&base[table->entries]); @@ -570,15 +565,17 @@ static tuple_flat_t _dir_sub_flat_lookup(IPLOOKUP* ip, TABLE_PTR table_ptr) } /* Lookup information associated with the value "ip" */ -tuple_flat_t sfrt_dir_flat_lookup(const sfip_t* ip, TABLE_PTR table_ptr) +tuple_flat_t sfrt_dir_flat_lookup(const uint32_t* addr, int numAddrDwords, TABLE_PTR table_ptr) { dir_table_flat_t* root; uint8_t* base = (uint8_t*)segment_basePtr(); + uint32_t h_addr[4]; + int i; IPLOOKUP iplu; - iplu.ip = ip; + iplu.addr = h_addr; iplu.bits = 0; - if (!table_ptr ) + if (!table_ptr) { tuple_flat_t ret = { 0, 0 }; return ret; @@ -592,6 +589,11 @@ tuple_flat_t sfrt_dir_flat_lookup(const sfip_t* ip, TABLE_PTR table_ptr) return ret; } + for (i = 0; i < numAddrDwords; i++) + h_addr[i] = ntohl(addr[i]); + while (i < 4) + h_addr[i++] = 0; + return _dir_sub_flat_lookup(&iplu, root->sub_table); } diff --git a/src/sfrt/sfrt_flat_dir.h b/src/sfrt/sfrt_flat_dir.h index dfc3fbdc7..03ebefdba 100644 --- a/src/sfrt/sfrt_flat_dir.h +++ b/src/sfrt/sfrt_flat_dir.h @@ -70,9 +70,9 @@ typedef struct 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 sfip_t* ip, TABLE_PTR table); -int sfrt_dir_flat_insert(const sfip_t *ip, int len, word data_index, -int behavior, TABLE_PTR, updateEntryInfoFunc updateEntry, INFO *data); +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); uint32_t sfrt_dir_flat_usage(TABLE_PTR); #endif /* SFRT_FLAT_DIR_H */ diff --git a/src/sfrt/sfrt_test.cc b/src/sfrt/sfrt_test.cc index 151e5369b..dd2e7e618 100644 --- a/src/sfrt/sfrt_test.cc +++ b/src/sfrt/sfrt_test.cc @@ -20,7 +20,7 @@ #include "catch/catch.hpp" #include "catch/unit_test.h" -#include "sfip/sf_ip.h" +#include "sfip/sf_cidr.h" #include "utils/util.h" #include "sfrt.h" @@ -75,8 +75,8 @@ static void test_sfrt_remove_after_insert() for (index=0; indexip_str, &ip); + ip.set(ip_entry->ip_str); ip2_str = snort_strdup(ip_entry->ip_str); p = strchr(ip2_str, '/'); @@ -96,20 +96,20 @@ static void test_sfrt_remove_after_insert() { *p = 0; } - sfip_pton(ip2_str, &ip2); + ip2.set(ip2_str); snort_free(ip2_str); } if ( s_debug ) { - printf("Insert IP addr: %s, family: %d\n", sfip_to_str(&ip), ip.family); + printf("Insert IP addr: %s, family: %d\n", ip.get_addr()->ntoa(), ip.get_family()); } - CHECK(sfrt_insert(&ip, ip.bits, &(ip_entry->value), RT_FAVOR_TIME, dir) == + CHECK(sfrt_insert(&ip, ip.get_bits(), &(ip_entry->value), RT_FAVOR_TIME, dir) == RT_SUCCESS); // "sfrt_insert()" if ( s_debug ) { - printf("Lookup IP addr: %s, family: %d\n", sfip_to_str(&ip2), ip2.family); + printf("Lookup IP addr: %s, family: %d\n", ip2.ntoa(), ip2.get_family()); } result = (int*)sfrt_lookup(&ip2, dir); if ( s_debug ) @@ -124,11 +124,11 @@ static void test_sfrt_remove_after_insert() if ( s_debug ) { - printf("IP addr: %s, family: %d\n", sfip_to_str(&ip), ip.family); + printf("IP addr: %s, family: %d\n", ip.get_addr()->ntoa(), ip.get_family()); printf("value input: %d, output: %d\n", ip_entry->value, *result); } - CHECK(sfrt_remove(&ip, ip.bits, (void**)&result, RT_FAVOR_TIME, dir) == RT_SUCCESS); + CHECK(sfrt_remove(&ip, ip.get_bits(), (void**)&result, RT_FAVOR_TIME, dir) == RT_SUCCESS); CHECK(result != NULL); //sfrt_remove()" val = *result; @@ -136,7 +136,7 @@ static void test_sfrt_remove_after_insert() printf("value expected: %d, actual: %d\n", ip_entry->value, val); CHECK(val == ip_entry->value); //sfrt_remove(): value return" - CHECK(sfrt_lookup(&ip, dir) == NULL); // "sfrt_lookup(): value return" + CHECK(sfrt_lookup(ip.get_addr(), dir) == NULL); // "sfrt_lookup(): value return" } if ( s_debug ) @@ -167,8 +167,8 @@ static void test_sfrt_remove_after_insert_all() /*insert all entries*/ for (index=0; indexip_str, &ip); + ip.set(ip_entry->ip_str); ip2_str = snort_strdup(ip_entry->ip_str); p = strchr(ip2_str, '/'); @@ -187,14 +187,14 @@ static void test_sfrt_remove_after_insert_all() { *p = 0; } - sfip_pton(ip2_str, &ip2); + ip2.set(ip2_str); snort_free(ip2_str); } - CHECK(sfrt_insert(&ip, ip.bits, &(ip_entry->value), RT_FAVOR_TIME, dir) == + CHECK(sfrt_insert(&ip, ip.get_bits(), &(ip_entry->value), RT_FAVOR_TIME, dir) == RT_SUCCESS); // "sfrt_insert()" - result = (int*)sfrt_lookup(&ip, dir); + result = (int*)sfrt_lookup(ip.get_addr(), dir); if ( s_debug ) printf("value input: %d, output: %d\n", ip_entry->value, result ? *result : -1); @@ -211,23 +211,23 @@ static void test_sfrt_remove_after_insert_all() /*remove all entries*/ for (index=0; indexip_str) - sfip_pton(ip_entry->ip_str, &ip); + ip.set(ip_entry->ip_str); - CHECK(sfrt_remove(&ip, ip.bits, (void**)&result, RT_FAVOR_TIME, dir) == RT_SUCCESS); + CHECK(sfrt_remove(&ip, ip.get_bits(), (void**)&result, RT_FAVOR_TIME, dir) == RT_SUCCESS); 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, dir)); + CHECK(!sfrt_lookup(ip.get_addr(), dir)); /*check the next entry still exist*/ if (index + 1 < num_entries) @@ -235,8 +235,8 @@ static void test_sfrt_remove_after_insert_all() ip_entry = &(ip_lists[index + 1]); /*Parse IP*/ if (ip_entry->ip_str) - sfip_pton(ip_entry->ip_str, &ip); - CHECK(sfrt_lookup(&ip, dir)); // "sfrt_lookup(): value return" + ip.set(ip_entry->ip_str); + CHECK(sfrt_lookup(ip.get_addr(), dir)); // "sfrt_lookup(): value return" } } diff --git a/src/stream/base/stream_ha.cc b/src/stream/base/stream_ha.cc index a3ee4421a..cf2bb869e 100644 --- a/src/stream/base/stream_ha.cc +++ b/src/stream/base/stream_ha.cc @@ -65,10 +65,10 @@ static Flow* protocol_create_session(FlowKey* key) static bool is_client_lower(Flow* flow) { - if (sfip_fast_lt6(&(flow->client_ip), &(flow->server_ip))) + if (flow->client_ip.fast_lt6(flow->server_ip)) return true; - if (sfip_fast_lt6(&(flow->server_ip), &(flow->client_ip))) + if (flow->server_ip.fast_lt6(flow->client_ip)) return false; switch (flow->key->pkt_type) @@ -112,15 +112,15 @@ bool StreamHAClient::consume(Flow*& flow, FlowKey* key, HAMessage* msg) int family = (hac->flags & SessionHAContent::FLAG_IP6) ? AF_INET6 : AF_INET; if ( hac->flags & SessionHAContent::FLAG_LOW ) { - sfip_set_raw(&(flow->server_ip), flow->key->ip_l, family); - sfip_set_raw(&(flow->client_ip), flow->key->ip_h, family); + flow->server_ip.set(flow->key->ip_l, family); + flow->client_ip.set(flow->key->ip_h, family); flow->server_port = flow->key->port_l; flow->client_port = flow->key->port_h; } else { - sfip_set_raw(&(flow->client_ip), flow->key->ip_l, family); - sfip_set_raw(&(flow->server_ip), flow->key->ip_h, family); + flow->client_ip.set(flow->key->ip_l, family); + flow->server_ip.set(flow->key->ip_h, family); flow->client_port = flow->key->port_l; flow->server_port = flow->key->port_h; } diff --git a/src/stream/icmp/icmp_session.cc b/src/stream/icmp/icmp_session.cc index c0287345a..5211ad2ef 100644 --- a/src/stream/icmp/icmp_session.cc +++ b/src/stream/icmp/icmp_session.cc @@ -73,8 +73,8 @@ static int ProcessIcmpUnreach(Packet* p) Flow* ssn = NULL; uint16_t sport; uint16_t dport; - const sfip_t* src; - const sfip_t* dst; + const SfIp* src; + const SfIp* dst; ip::IpApi iph; /* Set the Ip API to the embedded IP Header. */ @@ -109,16 +109,16 @@ static int ProcessIcmpUnreach(Packet* p) dport = 0; } - if (sfip_fast_lt6(src, dst)) + if (src->fast_lt6(*dst)) { - COPY4(skey.ip_l, src->ip32); + COPY4(skey.ip_l, src->get_ip6_ptr()); skey.port_l = sport; - COPY4(skey.ip_h, dst->ip32); + COPY4(skey.ip_h, dst->get_ip6_ptr()); skey.port_h = dport; } - else if (sfip_equals(iph.get_src(), iph.get_dst())) + else if (iph.get_src()->equals(*iph.get_dst())) { - COPY4(skey.ip_l, src->ip32); + COPY4(skey.ip_l, src->get_ip6_ptr()); COPY4(skey.ip_h, skey.ip_l); if (sport < dport) { @@ -133,8 +133,8 @@ static int ProcessIcmpUnreach(Packet* p) } else { - COPY4(skey.ip_l, dst->ip32); - COPY4(skey.ip_h, src->ip32); + COPY4(skey.ip_l, dst->get_ip6_ptr()); + COPY4(skey.ip_h, src->get_ip6_ptr()); skey.port_l = dport; skey.port_h = sport; } @@ -225,9 +225,9 @@ int IcmpSession::process(Packet* p) #define icmp_sender_ip flow->client_ip #define icmp_responder_ip flow->server_ip -void IcmpSession::update_direction(char dir, const sfip_t* ip, uint16_t) +void IcmpSession::update_direction(char dir, const SfIp* ip, uint16_t) { - if (sfip_equals(&icmp_sender_ip, ip)) + if (icmp_sender_ip.equals(*ip)) { if ((dir == SSN_DIR_FROM_CLIENT) && (flow->ssn_state.direction == FROM_CLIENT)) { @@ -235,7 +235,7 @@ void IcmpSession::update_direction(char dir, const sfip_t* ip, uint16_t) return; } } - else if (sfip_equals(&icmp_responder_ip, ip)) + else if (icmp_responder_ip.equals(*ip)) { if ((dir == SSN_DIR_FROM_SERVER) && (flow->ssn_state.direction == FROM_SERVER)) { @@ -245,7 +245,7 @@ void IcmpSession::update_direction(char dir, const sfip_t* ip, uint16_t) } /* Swap them -- leave ssn->ssn_state.direction the same */ - sfip_t tmpIp = icmp_sender_ip; + SfIp tmpIp = icmp_sender_ip; icmp_sender_ip = icmp_responder_ip; icmp_responder_ip = tmpIp; } diff --git a/src/stream/icmp/icmp_session.h b/src/stream/icmp/icmp_session.h index 8d43c91e9..eb954c5fe 100644 --- a/src/stream/icmp/icmp_session.h +++ b/src/stream/icmp/icmp_session.h @@ -28,7 +28,7 @@ public: IcmpSession(Flow*); bool setup(Packet*) override; - void update_direction(char dir, const sfip_t*, uint16_t port) override; + void update_direction(char dir, const SfIp*, uint16_t port) override; int process(Packet*) override; void clear() override; diff --git a/src/stream/ip/ip_defrag.cc b/src/stream/ip/ip_defrag.cc index 55e5070a0..da4c4b0c1 100644 --- a/src/stream/ip/ip_defrag.cc +++ b/src/stream/ip/ip_defrag.cc @@ -95,6 +95,7 @@ #include "utils/stats.h" #include "detection/detect.h" #include "utils/safec.h" +#include "utils/util.h" /* D E F I N E S **************************************************/ diff --git a/src/stream/libtcp/tcp_stream_session.cc b/src/stream/libtcp/tcp_stream_session.cc index 3a1ff3577..b60a46c89 100644 --- a/src/stream/libtcp/tcp_stream_session.cc +++ b/src/stream/libtcp/tcp_stream_session.cc @@ -221,13 +221,13 @@ bool TcpStreamSession::are_packets_missing(uint8_t dir) return false; } -void TcpStreamSession::update_direction(char dir, const sfip_t* ip, uint16_t port) +void TcpStreamSession::update_direction(char dir, const SfIp* ip, uint16_t port) { - sfip_t tmpIp; + SfIp tmpIp; uint16_t tmpPort; TcpStreamTracker* tracker; - if (sfip_equals(&flow->client_ip, ip) && (flow->client_port == port)) + if (flow->client_ip.equals(*ip) && (flow->client_port == port)) { if ((dir == SSN_DIR_FROM_CLIENT) && (flow->ssn_state.direction == FROM_CLIENT)) { @@ -235,7 +235,7 @@ void TcpStreamSession::update_direction(char dir, const sfip_t* ip, uint16_t por return; } } - else if (sfip_equals(&flow->server_ip, ip) && (flow->server_port == port)) + else if (flow->server_ip.equals(*ip) && (flow->server_port == port)) { if ((dir == SSN_DIR_FROM_SERVER) && (flow->ssn_state.direction == FROM_SERVER)) { @@ -265,7 +265,7 @@ bool TcpStreamSession::add_alert(Packet* p, uint32_t gid, uint32_t sid) TcpStreamTracker* st; StreamAlertInfo* ai; - if (sfip_equals(p->ptrs.ip_api.get_src(), &flow->client_ip)) + if (p->ptrs.ip_api.get_src()->equals(flow->client_ip)) st = server; else st = client; @@ -291,7 +291,7 @@ bool TcpStreamSession::check_alerted(Packet* p, uint32_t gid, uint32_t sid) TcpStreamTracker* st; - if (sfip_equals(p->ptrs.ip_api.get_src(), &flow->client_ip)) + if (p->ptrs.ip_api.get_src()->equals(flow->client_ip)) st = server; else st = client; @@ -317,7 +317,7 @@ int TcpStreamSession::update_alert(Packet* p, uint32_t gid, uint32_t sid, int i; uint32_t seq_num; - if (sfip_equals(p->ptrs.ip_api.get_src(), &flow->client_ip)) + if (p->ptrs.ip_api.get_src()->equals(flow->client_ip)) st = server; else st = client; diff --git a/src/stream/libtcp/tcp_stream_session.h b/src/stream/libtcp/tcp_stream_session.h index 84b4dd94a..99c18047e 100644 --- a/src/stream/libtcp/tcp_stream_session.h +++ b/src/stream/libtcp/tcp_stream_session.h @@ -54,7 +54,7 @@ public: bool are_packets_missing(uint8_t /*dir*/) override; uint8_t get_reassembly_direction() override; uint8_t missing_in_reassembled(uint8_t /*dir*/) override; - void update_direction(char dir, const sfip_t*, uint16_t port) override; + void update_direction(char dir, const SfIp*, uint16_t port) override; bool add_alert(Packet*, uint32_t gid, uint32_t sid) override; bool check_alerted(Packet*, uint32_t gid, uint32_t sid) override; int update_alert(Packet*, uint32_t /*gid*/, uint32_t /*sid*/, diff --git a/src/stream/stream.cc b/src/stream/stream.cc index 4f8425346..7bc86de76 100644 --- a/src/stream/stream.cc +++ b/src/stream/stream.cc @@ -98,8 +98,8 @@ void Stream::delete_flow(const FlowKey* key) Flow* Stream::get_flow( PktType type, IpProtocol proto, - const sfip_t* srcIP, uint16_t srcPort, - const sfip_t* dstIP, uint16_t dstPort, + const SfIp* srcIP, uint16_t srcPort, + const SfIp* dstIP, uint16_t dstPort, uint16_t vlan, uint32_t mplsId, uint16_t addressSpaceId) { FlowKey key; @@ -144,8 +144,8 @@ FlowData* Stream::get_flow_data( FlowData* Stream::get_flow_data( PktType type, IpProtocol proto, - const sfip_t* srcIP, uint16_t srcPort, - const sfip_t* dstIP, uint16_t dstPort, + const SfIp* srcIP, uint16_t srcPort, + const SfIp* dstIP, uint16_t dstPort, uint16_t vlan, uint32_t mplsId, uint16_t addressSpaceID, unsigned flow_id) { @@ -199,8 +199,8 @@ void Stream::check_flow_closed(Packet* p) int Stream::ignore_flow( const Packet* ctrlPkt, PktType type, IpProtocol ip_proto, - const sfip_t* srcIP, uint16_t srcPort, - const sfip_t* dstIP, uint16_t dstPort, + const SfIp* srcIP, uint16_t srcPort, + const SfIp* dstIP, uint16_t dstPort, char direction, uint32_t flow_id) { assert(flow_con); @@ -281,7 +281,7 @@ void Stream::resume_inspection(Flow* flow, char dir) } void Stream::update_direction( - Flow* flow, char dir, const sfip_t* ip, uint16_t port) + Flow* flow, char dir, const SfIp* ip, uint16_t port) { if (!flow) return; @@ -396,8 +396,8 @@ bool Stream::expected_flow(Flow* f, Packet* p) int Stream::set_application_protocol_id_expected( const Packet* ctrlPkt, PktType type, IpProtocol ip_proto, - const sfip_t* srcIP, uint16_t srcPort, - const sfip_t* dstIP, uint16_t dstPort, + const SfIp* srcIP, uint16_t srcPort, + const SfIp* dstIP, uint16_t dstPort, int16_t appId, FlowData* fd) { assert(flow_con); diff --git a/src/stream/stream.h b/src/stream/stream.h index 8555f3499..0afd15720 100644 --- a/src/stream/stream.h +++ b/src/stream/stream.h @@ -26,7 +26,6 @@ #include -#include "sfip/sfip_t.h" #include "protocols/packet.h" #include "flow/flow.h" #include "main/snort_types.h" @@ -55,6 +54,7 @@ "hpux11 | hpux10 | windows | win_2003 | vista | proxy" class Flow; +struct SfIp; typedef int (* LogFunction)(Flow*, uint8_t** buf, uint32_t* len, uint32_t* type); typedef void (* LogExtraData)(Flow*, void* config, LogFunction* funcs, @@ -108,8 +108,8 @@ public: // n-tuple parameters specified. Inspection will be turned off for this expected session // when it arrives. static int ignore_flow( - const Packet* ctrlPkt, PktType, IpProtocol, const sfip_t* srcIP, uint16_t srcPort, - const sfip_t* dstIP, uint16_t dstPort, char direction, uint32_t flow_id); + const Packet* ctrlPkt, PktType, IpProtocol, const SfIp* srcIP, uint16_t srcPort, + const SfIp* dstIP, uint16_t dstPort, char direction, uint32_t flow_id); // Resume inspection for flow. // FIXIT-L does resume work only for a flow that has been stopped by call to stop_inspection? @@ -182,14 +182,14 @@ public: // Turn off inspection for potential session. Adds session identifiers to a hash table. // TCP only. static int set_application_protocol_id_expected( - const Packet* ctrlPkt, PktType, IpProtocol, const sfip_t* srcIP, uint16_t srcPort, - const sfip_t* dstIP, uint16_t dstPort, int16_t appId, FlowData*); + const Packet* ctrlPkt, PktType, IpProtocol, const SfIp* srcIP, uint16_t srcPort, + const SfIp* dstIP, uint16_t dstPort, int16_t appId, FlowData*); // Get pointer to application data for a flow based on the lookup tuples for cases where // Snort does not have an active packet that is relevant. static FlowData* get_flow_data( PktType type, IpProtocol proto, - const sfip_t* a1, uint16_t p1, const sfip_t* a2, uint16_t p2, + const SfIp* a1, uint16_t p1, const SfIp* a2, uint16_t p2, uint16_t vlanId, uint32_t mplsId, uint16_t addrSpaceId, unsigned flow_id); // Get pointer to application data for a flow using the FlowKey as the lookup criteria @@ -199,7 +199,7 @@ public: // cases where Snort does not have an active packet that is relevant. static Flow* get_flow( PktType type, IpProtocol proto, - const sfip_t* a1, uint16_t p1, const sfip_t* a2, uint16_t p2, + const SfIp* a1, uint16_t p1, const SfIp* a2, uint16_t p2, uint16_t vlanId, uint32_t mplsId, uint16_t addrSpaceId); // Delete the session if it is in the closed session state. @@ -214,7 +214,7 @@ public: // Populate a session key from the Packet static void populate_flow_key(Packet*, FlowKey*); - static void update_direction(Flow*, char dir, const sfip_t* ip, uint16_t port); + static void update_direction(Flow*, char dir, const SfIp* ip, uint16_t port); static void set_application_protocol_id( Flow*, const struct HostAttributeEntry*, int direction); diff --git a/src/stream/tcp/tcp_session.cc b/src/stream/tcp/tcp_session.cc index 98a792331..cde50483d 100644 --- a/src/stream/tcp/tcp_session.cc +++ b/src/stream/tcp/tcp_session.cc @@ -492,7 +492,7 @@ void TcpSession::swap_trackers() client = server; server = trk; - sfip_t ip = flow->client_ip; + SfIp ip = flow->client_ip; flow->client_ip = flow->server_ip; flow->server_ip = ip; @@ -963,7 +963,7 @@ void TcpSession::set_extra_data(Packet* p, uint32_t xid) { TcpStreamTracker* st; - if (sfip_equals(p->ptrs.ip_api.get_src(), &flow->client_ip)) + if (p->ptrs.ip_api.get_src()->equals(flow->client_ip)) st = server; else st = client; @@ -975,7 +975,7 @@ void TcpSession::clear_extra_data(Packet* p, uint32_t xid) { TcpStreamTracker* st; - if (sfip_equals(p->ptrs.ip_api.get_src(), &flow->client_ip)) + if (p->ptrs.ip_api.get_src()->equals(flow->client_ip)) st = server; else st = client; diff --git a/src/stream/tcp/test/tcp_normalizer_test.cc b/src/stream/tcp/test/tcp_normalizer_test.cc index 17536cf01..2259c8114 100644 --- a/src/stream/tcp/test/tcp_normalizer_test.cc +++ b/src/stream/tcp/test/tcp_normalizer_test.cc @@ -45,7 +45,7 @@ public: TcpSession::TcpSession( Flow* ) : Session( flow ) { } TcpSession::~TcpSession( void ) { } bool TcpSession::setup(Packet*){ return true; } -void TcpSession::update_direction(char, sfip_t const*, unsigned short){ } +void TcpSession::update_direction(char, SfIp const*, unsigned short){ } int TcpSession::process(Packet*){ return 0; } void TcpSession::restart(Packet*){ } void TcpSession::precheck(Packet*){ } diff --git a/src/stream/udp/udp_session.cc b/src/stream/udp/udp_session.cc index 41bf4f130..ead652715 100644 --- a/src/stream/udp/udp_session.cc +++ b/src/stream/udp/udp_session.cc @@ -150,12 +150,12 @@ void UdpSession::clear() } void UdpSession::update_direction( - char dir, const sfip_t* ip, uint16_t port) + char dir, const SfIp* ip, uint16_t port) { - sfip_t tmpIp; + SfIp tmpIp; uint16_t tmpPort; - if (sfip_equals(&flow->client_ip, ip) && (flow->client_port == port)) + if (flow->client_ip.equals(*ip) && (flow->client_port == port)) { if ((dir == SSN_DIR_FROM_CLIENT) && (flow->ssn_state.direction == FROM_CLIENT)) { @@ -163,7 +163,7 @@ void UdpSession::update_direction( return; } } - else if (sfip_equals(&flow->server_ip, ip) && (flow->server_port == port)) + else if (flow->server_ip.equals(*ip) && (flow->server_port == port)) { if ((dir == SSN_DIR_FROM_SERVER) && (flow->ssn_state.direction == FROM_SERVER)) { diff --git a/src/stream/udp/udp_session.h b/src/stream/udp/udp_session.h index 7f1befb95..eeb670e16 100644 --- a/src/stream/udp/udp_session.h +++ b/src/stream/udp/udp_session.h @@ -29,7 +29,7 @@ public: UdpSession(Flow*); bool setup(Packet*) override; - void update_direction(char dir, const sfip_t*, uint16_t port) override; + void update_direction(char dir, const SfIp*, uint16_t port) override; int process(Packet*) override; void clear() override; diff --git a/src/stream/user/user_session.cc b/src/stream/user/user_session.cc index 6d305d5ad..f24baf480 100644 --- a/src/stream/user/user_session.cc +++ b/src/stream/user/user_session.cc @@ -320,7 +320,7 @@ void UserSession::start(Packet* p, Flow* flow) if ( (flow->ssn_state.session_flags & SSNFLAG_CLIENT_SWAP) && !(flow->ssn_state.session_flags & SSNFLAG_CLIENT_SWAPPED) ) { - sfip_t ip = flow->client_ip; + SfIp ip = flow->client_ip; uint16_t port = flow->client_port; flow->client_ip = flow->server_ip; @@ -500,7 +500,7 @@ int UserSession::process(Packet* p) // some will be deleted, some refactored, some implemented //------------------------------------------------------------------------- -void UserSession::update_direction(char /*dir*/, const sfip_t*, uint16_t /*port*/) { } +void UserSession::update_direction(char /*dir*/, const SfIp*, uint16_t /*port*/) { } bool UserSession::add_alert(Packet*, uint32_t /*gid*/, uint32_t /*sid*/) { return true; } bool UserSession::check_alerted(Packet*, uint32_t /*gid*/, uint32_t /*sid*/) { return false; } diff --git a/src/stream/user/user_session.h b/src/stream/user/user_session.h index 9a8e1fcde..c6300dca2 100644 --- a/src/stream/user/user_session.h +++ b/src/stream/user/user_session.h @@ -101,7 +101,7 @@ private: void update(Packet*, Flow*); void end(Packet*, Flow*); - void update_direction(char dir, const sfip_t*, uint16_t port) override; + void update_direction(char dir, const SfIp*, uint16_t port) override; bool add_alert(Packet*, uint32_t gid, uint32_t sid) override; bool check_alerted(Packet*, uint32_t gid, uint32_t sid) override; diff --git a/src/target_based/sftarget_data.h b/src/target_based/sftarget_data.h index 2c26d873b..2befb1860 100644 --- a/src/target_based/sftarget_data.h +++ b/src/target_based/sftarget_data.h @@ -22,7 +22,7 @@ #ifndef SFTARGET_DATA_H #define SFTARGET_DATA_H -#include "sfip/sfip_t.h" +#include "sfip/sf_cidr.h" #define SFAT_OK 0 #define SFAT_ERROR -1 @@ -68,7 +68,7 @@ struct HostInfo struct HostAttributeEntry { - sfip_t ipAddr; + SfCidr ipAddr; HostInfo hostInfo; ApplicationEntry* services; ApplicationEntry* clients; diff --git a/src/target_based/sftarget_reader.cc b/src/target_based/sftarget_reader.cc index 8652b02bc..4fbc7a2a1 100644 --- a/src/target_based/sftarget_reader.cc +++ b/src/target_based/sftarget_reader.cc @@ -46,6 +46,7 @@ #include "main/snort_config.h" #include "main/snort_debug.h" #include "parser/parser.h" +#include "protocols/packet.h" #include "utils/stats.h" #include "utils/util.h" #include "utils/util_net.h" @@ -186,7 +187,7 @@ int SFAT_AddApplicationData(HostAttributeEntry* host, ApplicationEntry* app) if ((app->fields & required_fields) != required_fields) { ParseError("Missing required field in Service attribute table for host %s", - inet_ntoa(&host->ipAddr)); + host->ipAddr.ntoa()); } AppendApplicationData(&host->services, app); @@ -205,8 +206,8 @@ static void PrintHostAttributeEntry(HostAttributeEntry* host) return; DebugFormat(DEBUG_ATTRIBUTE, "Host IP: %s/%d\n", - inet_ntoa(&host->ipAddr), - host->ipAddr.bits); + host->ipAddr.ntoa(), + host->ipAddr.get_bits()); DebugFormat(DEBUG_ATTRIBUTE, "\tPolicy Information: frag:%s (%hhu) stream: %s (%hhu)\n", @@ -252,14 +253,14 @@ int SFAT_AddHost(HostAttributeEntry* host) int SFAT_AddHostEntryToMap(HostAttributeEntry* host) { int ret; - sfip_t* ipAddr; + SfCidr* ipAddr; DEBUG_WRAP(PrintHostAttributeEntry(host); ); ipAddr = &host->ipAddr; assert(ipAddr); - ret = sfrt_insert(ipAddr, (unsigned char)ipAddr->bits, host, + ret = sfrt_insert(ipAddr, (unsigned char)ipAddr->get_bits(), host, RT_FAVOR_SPECIFIC, next_cfg->lookupTable); if (ret != RT_SUCCESS) @@ -291,12 +292,12 @@ int SFAT_AddHostEntryToMap(HostAttributeEntry* host) return ret == RT_SUCCESS ? SFAT_OK : SFAT_ERROR; } -HostAttributeEntry* SFAT_LookupHostEntryByIP(const sfip_t* ipAddr) +HostAttributeEntry* SFAT_LookupHostEntryByIP(const SfIp* ipAddr) { if ( !curr_cfg ) return NULL; - return (HostAttributeEntry*)sfrt_lookup((sfip_t*)ipAddr, curr_cfg->lookupTable); + return (HostAttributeEntry*)sfrt_lookup((SfIp*)ipAddr, curr_cfg->lookupTable); } HostAttributeEntry* SFAT_LookupHostEntryBySrc(Packet* p) @@ -361,7 +362,7 @@ tTargetBasedConfig* SFAT_Swap() return curr_cfg; } -void SFAT_UpdateApplicationProtocol(sfip_t* ipAddr, uint16_t port, uint16_t protocol, uint16_t id) +void SFAT_UpdateApplicationProtocol(SfIp* ipAddr, uint16_t port, uint16_t protocol, uint16_t id) { HostAttributeEntry* host_entry; ApplicationEntry* service; @@ -376,9 +377,9 @@ void SFAT_UpdateApplicationProtocol(sfip_t* ipAddr, uint16_t port, uint16_t prot return; host_entry = (HostAttributeEntry*)snort_calloc(sizeof(*host_entry)); - sfip_set_ip(&host_entry->ipAddr, ipAddr); + host_entry->ipAddr.set(*ipAddr); - if ((rval = sfrt_insert(ipAddr, (unsigned char)ipAddr->bits, host_entry, + if ((rval = sfrt_insert(&host_entry->ipAddr, (unsigned char)host_entry->ipAddr.get_bits(), host_entry, RT_FAVOR_SPECIFIC, curr_cfg->lookupTable)) != RT_SUCCESS) { FreeHostEntry(host_entry); diff --git a/src/target_based/sftarget_reader.h b/src/target_based/sftarget_reader.h index cbcbb24a6..40d6b5dc8 100644 --- a/src/target_based/sftarget_reader.h +++ b/src/target_based/sftarget_reader.h @@ -49,14 +49,14 @@ void FreeHostEntry(HostAttributeEntry* host); uint32_t SFAT_NumberOfHosts(); /* API Lookup functions, to be called by Stream & Frag */ -HostAttributeEntry* SFAT_LookupHostEntryByIP(const sfip_t* ipAddr); +HostAttributeEntry* SFAT_LookupHostEntryByIP(const SfIp* ipAddr); HostAttributeEntry* SFAT_LookupHostEntryBySrc(Packet* p); HostAttributeEntry* SFAT_LookupHostEntryByDst(Packet* p); #if 0 int SFAT_AddApplicationData(HostAttributeEntry*, struct ApplicationEntry*); #endif -void SFAT_UpdateApplicationProtocol(sfip_t*, uint16_t port, uint16_t protocol, uint16_t id); +void SFAT_UpdateApplicationProtocol(SfIp*, uint16_t port, uint16_t protocol, uint16_t id); // reload functions struct tTargetBasedConfig; diff --git a/src/utils/util.cc b/src/utils/util.cc index a05741386..f95770860 100644 --- a/src/utils/util.cc +++ b/src/utils/util.cc @@ -33,6 +33,7 @@ #include #include #include +#include #include #ifdef HAVE_LZMA @@ -55,6 +56,7 @@ extern "C" { #include "main/snort_config.h" #include "main/snort_debug.h" #include "packet_io/sfdaq.h" +#include "protocols/packet.h" // For NUM_IP_PROTOS #ifdef PATH_MAX #define PATH_MAX_UTIL PATH_MAX diff --git a/src/utils/util_net.cc b/src/utils/util_net.cc index 2dd1643f2..815eabb11 100644 --- a/src/utils/util_net.cc +++ b/src/utils/util_net.cc @@ -23,12 +23,10 @@ #include "config.h" #endif +#include #include #include -/* for inet_ntoa */ -#include - #include "main/thread.h" #include "util.h" @@ -38,7 +36,7 @@ * * @param ip ip in NETWORK BYTE ORDER */ -char* inet_ntoax(const sfip_t* ip) +char* inet_ntoax(const SfIp* ip) { static THREAD_LOCAL char ip_buf1[INET6_ADDRSTRLEN]; static THREAD_LOCAL char ip_buf2[INET6_ADDRSTRLEN]; @@ -54,23 +52,9 @@ char* inet_ntoax(const sfip_t* ip) buf_num ^= 1; ip_buf[0] = 0; - SnortSnprintf(ip_buf, buf_size, "%s", inet_ntoa(ip)); + if (ip) + SnortSnprintf(ip_buf, buf_size, "%s", ip->ntoa()); return ip_buf; } -#ifdef TEST_UTIL_NET -int main() -{ - uint32_t ip1 = htonl(0xFF00FF00); - uint32_t ip2 = htonl(0xFFAAFFAA); - - printf("%s -> %s\n", inet_ntoax(ip1), inet_ntoax(ip2)); - - /* the following one is invalid and will break the first one*/ - printf("%s -> %s -> %s\n", inet_ntoax(ip1), inet_ntoax(ip2), inet_ntoax(ip2)); - return 0; -} - -#endif /* TEST_UTIL_NET */ - diff --git a/src/utils/util_net.h b/src/utils/util_net.h index 7c512a58c..4556fcda2 100644 --- a/src/utils/util_net.h +++ b/src/utils/util_net.h @@ -26,9 +26,9 @@ // Be aware that subsequent calls will overwrite the memory that is pointed to #include "main/snort_types.h" -#include "sfip/sfip_t.h" +#include "sfip/sf_ip.h" -SO_PUBLIC char* inet_ntoax(const sfip_t*); +SO_PUBLIC char* inet_ntoax(const SfIp*); #endif -- 2.47.2