From: Russ Combs (rucombs) Date: Mon, 30 Oct 2017 20:58:46 +0000 (-0400) Subject: Merge pull request #1054 in SNORT/snort3 from crc_cppcheck to master X-Git-Tag: 3.0.0-240~1 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=1c8d6d53f794694672381d5e1dc5785c470616c2;p=thirdparty%2Fsnort3.git Merge pull request #1054 in SNORT/snort3 from crc_cppcheck to master Squashed commit of the following: commit 80f5dfd68a2315a3d95a5a5b5ba4db3432798181 Author: Russ Combs Date: Mon Oct 30 13:35:10 2017 -0400 cppcheck: more scope reduction commit d0c67534b4b471c2a6ec74b36a0c98874b4bd0db Author: Russ Combs Date: Sun Oct 29 16:49:43 2017 -0400 cppcheck: fix a few warnings commit e25a24bc7f7ae97844e5d08096335168bde7ccff Author: Russ Combs Date: Sun Oct 29 13:34:20 2017 -0400 warnings: use fallthrough comments commit 896fd132ca162ded29243968fe12249c7ea45923 Author: Russ Combs Date: Sun Oct 29 12:24:34 2017 -0400 memory: fix xcode print format warning commit aeb9f6caa227f9e05c2737b07d21689d30359529 Author: Russ Combs Date: Fri Oct 27 22:36:08 2017 -0400 content: fix relative loop condition commit 6f95a732b68652d32ac9aded68e47b4fd8ead55b Author: Russ Combs Date: Fri Oct 27 09:01:39 2017 -0400 cd_icmp6: fix encoded cksum calculation commit e9e945ca1f37a6274c24cc7cc9e602aa5d0fea58 Author: Russ Combs Date: Fri Oct 27 07:28:05 2017 -0400 appid: fix build warning commit 4b29f5d7702575335a687d2debd023c6bca16990 Author: Russ Combs Date: Wed Oct 25 21:26:56 2017 -0400 active: fix packet modify vs resize handling commit 79ca752e85edae2d623143b3458ba4ebdfa98f80 Author: Russ Combs Date: Wed Oct 25 21:05:31 2017 -0400 cppcheck: reduce variable scopes commit 58e172c5fa9c15bcd82ab4a8bedc7755d5e0ecab Author: Russ Combs Date: Wed Oct 25 21:04:47 2017 -0400 cppcheck: fix non-style issues commit 1ba4c8614b1dd9701fa817aad1396a8f058ff037 Author: Russ Combs Date: Wed Oct 25 12:25:27 2017 -0400 manual: fix some typos --- diff --git a/doc/port_scan.txt b/doc/port_scan.txt index 889fc1ca4..824e860b1 100644 --- a/doc/port_scan.txt +++ b/doc/port_scan.txt @@ -142,7 +142,7 @@ target host, and because of the nature of error responses, this setting should see very few false positives. However, this setting will never trigger a Filtered Scan alert because of a lack of error responses. This setting is based on a static time window of 60 -seconds, afterwhich this window is reset. +seconds, after which this window is reset. "Medium" alerts track Connection Counts, and so will generate Filtered Scan alerts. This setting may false positive on active @@ -178,7 +178,7 @@ ignore_scanners option. If the host is generating portscan alerts ignore_scanned option. Filtered scan alerts are much more prone to false positives. -When deteriming false positives, the alert type is very important. +When determining false positives, the alert type is very important. Most of the false positives that Portscan may generate are of the filtered scan alert type. So be much more suspicious of filtered portscans. Many times this just indicates that a host was very diff --git a/doc/style.txt b/doc/style.txt index f95957584..53668efae 100644 --- a/doc/style.txt +++ b/doc/style.txt @@ -116,6 +116,11 @@ yet firm so feedback is welcome to get something we can live with. * Each header should have a comment immediately after the header guard to give an overview of the file so the reader knows what's going on. +* Use the following comment on switch cases that intentionally fall through + to the next case to suppress compiler warning on known valid cases: + + // fallthrough + === Logging * Messages intended for the user should not look like debug messages. Eg, diff --git a/extra/src/inspectors/reg_test/reg_test.cc b/extra/src/inspectors/reg_test/reg_test.cc index 2f7058ebe..dc38fff62 100644 --- a/extra/src/inspectors/reg_test/reg_test.cc +++ b/extra/src/inspectors/reg_test/reg_test.cc @@ -130,12 +130,13 @@ void RtiService::show(SnortConfig*) void RtiService::do_daq_packet_retry_test(Packet* p) { - static bool retry_packet = true; - static bool expect_retry_packet = false; if (p->dsize) { if (p->data[0] == 'A') { + static bool retry_packet = true; + static bool expect_retry_packet = false; + if (retry_packet) { Active::daq_retry_packet(p); diff --git a/extra/src/search_engines/lowmem/sfksearch.cc b/extra/src/search_engines/lowmem/sfksearch.cc index 8945bf104..3b8a7009c 100644 --- a/extra/src/search_engines/lowmem/sfksearch.cc +++ b/extra/src/search_engines/lowmem/sfksearch.cc @@ -408,13 +408,10 @@ static void Build_Bad_Character_Shifts(KTRIE_STRUCT* kt) */ for ( plist=kt->patrn; plist; plist=plist->next ) { - int shift, cindex; - for ( int k=0; kbcSize; k++ ) { - shift = kt->bcSize - 1 - k; - - cindex = plist->P[ k ]; + int shift = kt->bcSize - 1 - k; + int cindex = plist->P[ k ]; if ( shift < kt->bcShift[ cindex ] ) { @@ -475,13 +472,13 @@ static int KTrieBuildMatchStateNode( static int KTrieBuildMatchStateTrees(SnortConfig* sc, KTRIE_STRUCT* ts) { - int i, cnt = 0; - KTRIENODE* root; + int cnt = 0; /* Find the states that have a MatchList */ - for (i = 0; i < KTRIE_ROOT_NODES; i++) + for (int i = 0; i < KTRIE_ROOT_NODES; i++) { - root = ts->root[i]; + KTRIENODE* root = ts->root[i]; + /* each and every prefix match at this root*/ if ( root and ts->agent ) { @@ -643,7 +640,6 @@ static inline int KTrieSearchNoBC( static inline int KTrieSearchBC( KTRIE_STRUCT* ks, const uint8_t* Tx, int n, MpseMatch match, void* context) { - int tshift; const uint8_t* Tend; const uint8_t* T, * bT; int nfound = 0; @@ -661,6 +657,8 @@ static inline int KTrieSearchBC( for (; T <= Tend; n--, T++, Tx++ ) { + int tshift; + while ( (tshift = bcShift[ *( T + bcSize ) ]) > 0 ) { T += tshift; diff --git a/src/codecs/ip/cd_gre.cc b/src/codecs/ip/cd_gre.cc index b33325cc1..ee81ff5c4 100644 --- a/src/codecs/ip/cd_gre.cc +++ b/src/codecs/ip/cd_gre.cc @@ -131,25 +131,21 @@ bool GreCodec::decode(const RawData& raw, CodecData& codec, DecodeData&) * Source Route Entries */ if (GRE_ROUTE(greh)) { - uint16_t sre_addrfamily; - uint8_t sre_offset; - uint8_t sre_length; - const uint8_t* sre_ptr; - - sre_ptr = raw.data + len; + const uint8_t* sre_ptr = raw.data + len; while (true) { len += GRE_SRE_HEADER_LEN; + if (len > raw.len) break; - sre_addrfamily = ntohs(*((const uint16_t*)sre_ptr)); - sre_ptr += sizeof(sre_addrfamily); + uint16_t sre_addrfamily = ntohs(*((const uint16_t*)sre_ptr)); - sre_ptr += sizeof(sre_offset); + sre_ptr += sizeof(sre_addrfamily); + sre_ptr += sizeof(uint8_t); // sre_offset - sre_length = *((const uint8_t*)sre_ptr); + uint8_t sre_length = *((const uint8_t*)sre_ptr); sre_ptr += sizeof(sre_length); if ((sre_addrfamily == 0) && (sre_length == 0)) diff --git a/src/codecs/ip/cd_icmp6.cc b/src/codecs/ip/cd_icmp6.cc index d67b8bab8..3f7cb91ee 100644 --- a/src/codecs/ip/cd_icmp6.cc +++ b/src/codecs/ip/cd_icmp6.cc @@ -329,10 +329,10 @@ struct IcmpHdr } // namespace void Icmp6Codec::update(const ip::IpApi& api, const EncodeFlags flags, - uint8_t* raw_pkt, uint16_t /*lyr_len*/, uint32_t& updated_len) + uint8_t* raw_pkt, uint16_t lyr_len, uint32_t& updated_len) { IcmpHdr* h = reinterpret_cast(raw_pkt); - updated_len += sizeof(*h); + updated_len += lyr_len; if ( !(flags & UPD_COOKED) || (flags & UPD_REBUILT_FRAG) ) { diff --git a/src/codecs/ip/checksum.h b/src/codecs/ip/checksum.h index 564b5ac99..45385b1d1 100644 --- a/src/codecs/ip/checksum.h +++ b/src/codecs/ip/checksum.h @@ -90,12 +90,11 @@ struct Psuedoheader6Union inline uint16_t cksum_add(const uint16_t* buf, std::size_t len, uint32_t cksum) { const uint16_t* sp = buf; - std::size_t n, sn; if (len > 1 ) { - sn = ((len / 2) & 0xF); // == len/2 % 16 - n = (((len / 2) + 15) / 16); // ceiling of (len / 2) / 16 + std::size_t sn = ((len / 2) & 0xF); // == len/2 % 16 + std::size_t n = (((len / 2) + 15) / 16); // ceiling of (len / 2) / 16 switch (sn) { diff --git a/src/codecs/link/cd_erspan3.cc b/src/codecs/link/cd_erspan3.cc index 5b7100206..1a6143d89 100644 --- a/src/codecs/link/cd_erspan3.cc +++ b/src/codecs/link/cd_erspan3.cc @@ -57,7 +57,7 @@ struct ERSpanType3Hdr { uint16_t ver_vlan; uint16_t flags_spanId; - uint32_t time_stamp; // adding an underscore so function can be called timestamp() + uint32_t timestamp; uint16_t pad0; uint16_t pad1; uint32_t pad2; @@ -65,15 +65,6 @@ struct ERSpanType3Hdr inline uint16_t version() const { return ntohs(ver_vlan) >> 12; } - - inline uint16_t vlan() const - { return ntohs(ver_vlan) & 0xfff; } - - inline uint16_t span_id() const - { return ntohs(flags_spanId) & 0x03ff; } - - inline uint32_t timestamp() const - { return ntohs(time_stamp); } }; } // anonymous namespace diff --git a/src/codecs/link/cd_mpls.cc b/src/codecs/link/cd_mpls.cc index 554158468..2105a086a 100644 --- a/src/codecs/link/cd_mpls.cc +++ b/src/codecs/link/cd_mpls.cc @@ -148,12 +148,7 @@ void MplsCodec::get_protocol_ids(std::vector& v) bool MplsCodec::decode(const RawData& raw, CodecData& codec, DecodeData& snort) { - uint32_t mpls_h; - uint32_t label; - - uint8_t exp; uint8_t bos = 0; - uint8_t ttl; uint8_t chainLen = 0; uint32_t stack_len = raw.len; @@ -173,12 +168,12 @@ bool MplsCodec::decode(const RawData& raw, CodecData& codec, DecodeData& snort) return false; } - mpls_h = ntohl(*tmpMplsHdr); - ttl = (uint8_t)(mpls_h & 0x000000FF); + uint32_t mpls_h = ntohl(*tmpMplsHdr); + uint8_t ttl = (uint8_t)(mpls_h & 0x000000FF); mpls_h = mpls_h>>8; bos = (uint8_t)(mpls_h & 0x00000001); - exp = (uint8_t)(mpls_h & 0x0000000E); - label = (mpls_h>>4) & 0x000FFFFF; + uint8_t exp = (uint8_t)(mpls_h & 0x0000000E); + uint32_t label = (mpls_h>>4) & 0x000FFFFF; if ((label& v) bool GtpCodec::decode(const RawData& raw, CodecData& codec, DecodeData& dd) { - uint8_t next_hdr_type; uint8_t version; - uint8_t ip_ver; uint16_t len; const GTPHdr* const hdr = reinterpret_cast(raw.data); @@ -137,7 +135,7 @@ bool GtpCodec::decode(const RawData& raw, CodecData& codec, DecodeData& dd) codec_event(codec, DECODE_GTP_BAD_LEN); return false; } - next_hdr_type = *(raw.data + len - 1); + uint8_t next_hdr_type = *(raw.data + len - 1); /*Check extension headers*/ while (next_hdr_type) @@ -198,8 +196,8 @@ bool GtpCodec::decode(const RawData& raw, CodecData& codec, DecodeData& dd) if (raw.len > 0) { codec.codec_flags |= CODEC_ENCAP_LAYER; + uint8_t ip_ver = *(raw.data + len) & 0xF0; - ip_ver = *(raw.data + len) & 0xF0; if (ip_ver == 0x40) codec.next_prot_id = ProtocolId::IPIP; else if (ip_ver == 0x60) diff --git a/src/connectors/file_connector/test/file_connector_test.cc b/src/connectors/file_connector/test/file_connector_test.cc index 6c2499612..c5b5758a9 100644 --- a/src/connectors/file_connector/test/file_connector_test.cc +++ b/src/connectors/file_connector/test/file_connector_test.cc @@ -182,11 +182,6 @@ TEST_GROUP(file_connector_tinit_tterm) } }; -TEST(file_connector_tinit_tterm, null) -{ - CHECK(1==1); -} - TEST(file_connector_tinit_tterm, alloc_discard) { const uint8_t* data = nullptr; diff --git a/src/decompress/file_decomp_pdf.cc b/src/decompress/file_decomp_pdf.cc index 218d551a9..ad9127ebf 100644 --- a/src/decompress/file_decomp_pdf.cc +++ b/src/decompress/file_decomp_pdf.cc @@ -189,7 +189,6 @@ static fd_status_t Process_Filter_Spec(fd_session_t* SessionPtr) bool Found_Token = false; uint8_t* Filter; uint8_t Length; - uint8_t c; int Index; fd_status_t Ret_Code = File_Decomp_OK; @@ -202,7 +201,7 @@ static fd_status_t Process_Filter_Spec(fd_session_t* SessionPtr) for ( Index=0; IndexFilter_Spec_Index; Index++ ) { - c = p->Filter_Spec_Buf[Index]; + const uint8_t c = p->Filter_Spec_Buf[Index]; if ( (c == 0) || (strchr( (const char*)Delim_Str, (int)c) != nullptr) ) { @@ -332,7 +331,6 @@ static inline fd_PDF_Parse_Stack_p_t Get_Previous_State(fd_PDF_Parse_p_t p) only explore Dictionary objects within Indirect Objects. */ static inline fd_status_t Handle_State_DICT_OBJECT(fd_session_t* SessionPtr, uint8_t c) { - char Filter_Tok[] = TOK_DICT_FILT; fd_PDF_Parse_p_t p = &(SessionPtr->PDF->Parse); /* enter with c being an EOL from the ind obj state */ @@ -398,6 +396,8 @@ static inline fd_status_t Handle_State_DICT_OBJECT(fd_session_t* SessionPtr, uin and handles other diversion such as nested Dict objects. If the /Filter token doesn't exist then we don't fill the Filter_Spec_Buf[]. If in skip mode, no need to look for token. */ + char Filter_Tok[] = TOK_DICT_FILT; + if ( (p->Sub_State == P_DICT_ACTIVE) && c == Filter_Tok[p->Elem_Index++] ) { if ( Filter_Tok[p->Elem_Index] == '\0' ) @@ -823,7 +823,6 @@ static fd_status_t Locate_Stream_Beginning(fd_session_t* SessionPtr) { fd_PDF_Parse_p_t p = &(SessionPtr->PDF->Parse); fd_status_t Ret_Code = File_Decomp_OK; - uint8_t c; while ( true ) { @@ -835,7 +834,7 @@ static fd_status_t Locate_Stream_Beginning(fd_session_t* SessionPtr) return( File_Decomp_BlockOut ); /* Get next byte in input queue */ - c = *SessionPtr->Next_In; + uint8_t c = *SessionPtr->Next_In; switch ( p->State ) { @@ -1080,10 +1079,9 @@ fd_status_t File_Decomp_PDF(fd_session_t* SessionPtr) else { SessionPtr->PDF->State = PDF_STATE_INIT_STREAM; - /* If we've located the beginning of stream, set new state - and fall into next state */ } } + // fallthrough case ( PDF_STATE_INIT_STREAM ): { @@ -1099,8 +1097,8 @@ fd_status_t File_Decomp_PDF(fd_session_t* SessionPtr) } SessionPtr->PDF->State = PDF_STATE_PROCESS_STREAM; - /* INTENTIONAL FALL-THROUGH INTO PDF_STATE_PROCESS_STREAM CASE. */ } + // fallthrough case ( PDF_STATE_PROCESS_STREAM ): { diff --git a/src/decompress/file_decomp_swf.cc b/src/decompress/file_decomp_swf.cc index da26b6afe..d5ce21903 100644 --- a/src/decompress/file_decomp_swf.cc +++ b/src/decompress/file_decomp_swf.cc @@ -295,8 +295,9 @@ fd_status_t File_Decomp_SWF(fd_session_t* SessionPtr) } SessionPtr->SWF->State = SWF_STATE_PROC_HEADER; - /* INTENTIONAL FALL-THROUGH INTO SWF_STATE_PROC_HEADER CASE. */ } + // fallthrough + case ( SWF_STATE_PROC_HEADER ): { #ifdef HAVE_LZMA @@ -309,8 +310,9 @@ fd_status_t File_Decomp_SWF(fd_session_t* SessionPtr) #endif SessionPtr->SWF->State = SWF_STATE_DATA; - /* INTENTIONAL FALL-THROUGH INTO SWF_STATE_DATA CASE. */ } + // fallthrough + case ( SWF_STATE_DATA ): { Ret_Code = Decomp(SessionPtr); diff --git a/src/detection/detection_options.cc b/src/detection/detection_options.cc index d618e6c1d..cbc53cfe6 100644 --- a/src/detection/detection_options.cc +++ b/src/detection/detection_options.cc @@ -312,10 +312,8 @@ void print_option_tree(detection_option_tree_node_t* node, int level) opt = buf; } - unsigned int indent = level + strlen(opt); - DebugFormatNoFileLine(DEBUG_DETECT, "%3d %3d %p %*s\n", - level, node->num_children, node->option_data, indent, opt); + level, node->num_children, node->option_data, level + strlen(opt), opt); for ( int i=0; inum_children; i++ ) print_option_tree(node->children[i], level+1); @@ -399,14 +397,11 @@ int detection_option_node_evaluate( state.last_check.rebuild_flag = p->packet_flags & PKT_REBUILT_STREAM; // Save some stuff off for repeated pattern tests - bool try_again = false; PmdLastCheck* content_last = nullptr; if ( node->option_type != RULE_OPTION_TYPE_LEAF_NODE ) { IpsOption* opt = (IpsOption*)node->option_data; - try_again = opt->retry(); - PatternMatchData* pmd = opt->get_pattern(0, RULE_WO_DIR); if ( pmd and pmd->last_check ) @@ -696,7 +691,8 @@ int detection_option_node_evaluate( if ( continue_loop && rval == (int)IpsOption::MATCH && node->relative_children ) { - continue_loop = try_again; + IpsOption* opt = (IpsOption*)node->option_data; + continue_loop = opt->retry(cursor); } else continue_loop = false; @@ -727,7 +723,6 @@ int detection_option_node_evaluate( } state.last_check.result = result; - profile.stop(result != (int)IpsOption::NO_MATCH); return result; diff --git a/src/detection/fp_create.cc b/src/detection/fp_create.cc index 0d9d24326..8ed361071 100644 --- a/src/detection/fp_create.cc +++ b/src/detection/fp_create.cc @@ -140,7 +140,6 @@ static int otn_create_tree(OptTreeNode* otn, void** existing_tree) /* If child node does not match existing option_data, * Create a child branch from a given sub-node. */ void* option_data = opt_fp->ips_opt; - char found_child_match = 0; if (opt_fp->type == RULE_OPTION_TYPE_LEAF_NODE) { @@ -179,6 +178,8 @@ static int otn_create_tree(OptTreeNode* otn, void** existing_tree) } else { + bool found_child_match = false; + if (child->option_data != option_data) { if (!node) @@ -188,7 +189,7 @@ static int otn_create_tree(OptTreeNode* otn, void** existing_tree) child = root->children[i]; if (child->option_data == option_data) { - found_child_match = 1; + found_child_match = true; break; } } @@ -200,7 +201,7 @@ static int otn_create_tree(OptTreeNode* otn, void** existing_tree) child = node->children[i]; if (child->option_data == option_data) { - found_child_match = 1; + found_child_match = true; break; } } @@ -208,10 +209,10 @@ static int otn_create_tree(OptTreeNode* otn, void** existing_tree) } else { - found_child_match = 1; + found_child_match = true; } - if (found_child_match == 0) + if ( !found_child_match ) { /* No matching child node, create a new and add to array */ detection_option_tree_node_t** tmp_children; diff --git a/src/detection/tag.cc b/src/detection/tag.cc index cee5099b7..9005a40da 100644 --- a/src/detection/tag.cc +++ b/src/detection/tag.cc @@ -628,11 +628,11 @@ static int PruneTagCache(uint32_t thetime, int mustdie) } else { - TagNode* lru_node = nullptr; - while (pruned < mustdie && (sfxhash_count(ssn_tag_cache_ptr) > 0 || sfxhash_count(host_tag_cache_ptr) > 0)) { + TagNode* lru_node; + if ((lru_node = (TagNode*)sfxhash_lru(ssn_tag_cache_ptr)) != nullptr) { if (sfxhash_remove(ssn_tag_cache_ptr, lru_node) != SFXHASH_OK) diff --git a/src/file_api/file_flows.cc b/src/file_api/file_flows.cc index c23880c0d..b79ea40af 100644 --- a/src/file_api/file_flows.cc +++ b/src/file_api/file_flows.cc @@ -141,8 +141,6 @@ FileContext* FileFlows::get_file_context(uint64_t file_id, bool to_create) bool FileFlows::file_process(uint64_t file_id, const uint8_t* file_data, int data_size, uint64_t offset, FileDirection dir) { - int ret = 0; - int64_t file_depth = FileService::get_max_file_depth(); if ((file_depth < 0)or (offset > (uint64_t)file_depth)) @@ -171,8 +169,7 @@ bool FileFlows::file_process(uint64_t file_id, const uint8_t* file_data, { /* Just check file type and signature */ FilePosition position = SNORT_FILE_FULL; - ret = context->process(flow, file_data, data_size, position); - return ret; + return context->process(flow, file_data, data_size, position); } } diff --git a/src/file_api/file_lib.cc b/src/file_api/file_lib.cc index 4939b1af3..6389b914a 100644 --- a/src/file_api/file_lib.cc +++ b/src/file_api/file_lib.cc @@ -608,14 +608,13 @@ uint64_t FileContext::get_processed_bytes() void FileContext::print_file_data(FILE* fp, const uint8_t* data, int len, int max_depth) { char str[18]; - int i; - int pos; - char c; + int i, pos; if (max_depth < len) len = max_depth; fprintf(fp,"Show length: %d \n", len); + for (i=0, pos=0; igid == 1 ) /* patmatch rules gid, many rules */ { nrows= SFRF_GEN_ID_1_ROWS; @@ -298,8 +298,7 @@ int SFRF_ConfigAdd( } /* Add the pSidNode to the hash table */ - hstatus = sfghash_add(genHash, (void*)&key, pSidNode); - if ( hstatus ) + if ( sfghash_add(genHash, (void*)&key, pSidNode) ) { sflist_free(pSidNode->configNodeList); snort_free(pSidNode); @@ -573,7 +572,6 @@ int SFRF_TestThreshold( */ void SFRF_ShowObjects(RateFilterConfig* config) { - SFGHASH* genHash; tSFRFSidNode* pSidnode; tSFRFConfigNode* cfgNode; unsigned int gid; @@ -581,11 +579,10 @@ void SFRF_ShowObjects(RateFilterConfig* config) for ( gid=0; gid < SFRF_MAX_GENID; gid++ ) { - genHash = config->genHash [ gid ]; + SFGHASH* genHash = config->genHash [ gid ]; + if ( !genHash ) - { continue; - } printf("...GEN_ID = %u\n",gid); @@ -629,14 +626,12 @@ void SFRF_ShowObjects(RateFilterConfig* config) static int _checkSamplingPeriod( tSFRFConfigNode* cfgNode, tSFRFTrackingNode* dynNode, - time_t curTime - ) + time_t curTime) { - unsigned dt; - if ( cfgNode->seconds ) { - dt = (unsigned)(curTime - dynNode->tstart); + unsigned dt = (unsigned)(curTime - dynNode->tstart); + if ( dt >= cfgNode->seconds ) { // observation period is over, start a new one dynNode->tstart = curTime; diff --git a/src/filters/sfthd.cc b/src/filters/sfthd.cc index dbba912e2..bfab67324 100644 --- a/src/filters/sfthd.cc +++ b/src/filters/sfthd.cc @@ -297,8 +297,6 @@ static int sfthd_create_threshold_local( THD_ITEM* sfthd_item; THD_NODE* sfthd_node; tThdItemKey key; - int nrows; - int hstatus; PolicyId policy_id = get_network_policy()->policy_id; @@ -315,6 +313,8 @@ static int sfthd_create_threshold_local( /* Check for an existing 'gen_id' entry, if none found create one. */ if (thd_objs->sfthd_array[config->gen_id] == nullptr) { + int nrows; + if ( config->gen_id == 1 ) /* patmatch rules gen_id, many rules */ { nrows= THD_GEN_ID_1_ROWS; @@ -364,8 +364,7 @@ static int sfthd_create_threshold_local( } /* Add the sfthd_item to the hash table */ - hstatus = sfghash_add(sfthd_hash, (void*)&key, sfthd_item); - if ( hstatus ) + if ( sfghash_add(sfthd_hash, (void*)&key, sfthd_item) ) { sflist_free(sfthd_item->sfthd_node_list); snort_free(sfthd_item); @@ -1235,7 +1234,6 @@ global_test: */ int sfthd_show_objects(ThresholdObjects* thd_objs) { - SFGHASH* sfthd_hash; THD_ITEM* sfthd_item; THD_NODE* sfthd_node; unsigned gen_id; @@ -1243,8 +1241,9 @@ int sfthd_show_objects(ThresholdObjects* thd_objs) for (gen_id=0; gen_id < THD_MAX_GENID; gen_id++ ) { - sfthd_hash = thd_objs->sfthd_array[gen_id]; - if (sfthd_hash == NULL) + SFGHASH* sfthd_hash = thd_objs->sfthd_array[gen_id]; + + if ( !sfthd_hash ) continue; printf("...GEN_ID = %u\n",gen_id); diff --git a/src/flow/expect_cache.cc b/src/flow/expect_cache.cc index ca2512337..2fc3e133e 100644 --- a/src/flow/expect_cache.cc +++ b/src/flow/expect_cache.cc @@ -130,9 +130,6 @@ ExpectNode* ExpectCache::find_node_by_packet(Packet* p, FlowKey &key) bool reversed_key = key.init(type, ip_proto, dstIP, p->ptrs.dp, srcIP, p->ptrs.sp, vlanId, mplsId, addressSpaceId); - uint16_t port1; - uint16_t port2; - /* Lookup order: 1. Full match. @@ -149,6 +146,9 @@ ExpectNode* ExpectCache::find_node_by_packet(Packet* p, FlowKey &key) // FIXIT-M X This logic could fail if IPs were equal because the original key // would always have been created with a 0 for src or dst port and put the // known port in port_h. + uint16_t port1; + uint16_t port2; + if (reversed_key) { port1 = key.port_l; diff --git a/src/flow/ha.cc b/src/flow/ha.cc index a78075d7d..c5aa0dab1 100644 --- a/src/flow/ha.cc +++ b/src/flow/ha.cc @@ -423,13 +423,13 @@ static void consume_receive_message(HAMessage* msg) HighAvailability::HighAvailability(PortBitSet* ports, bool) { - SCPort port; using namespace std::placeholders; DebugMessage(DEBUG_HA,"HighAvailability::HighAvailability()\n"); // If we have ports, configure the side channel if ( ports != nullptr ) - for ( port = 0; port < ports->size(); port++ ) + { + for ( SCPort port = 0; port < ports->size(); port++ ) if ( ports->test(port) ) { sc = SideChannelManager::get_side_channel(port); @@ -448,7 +448,7 @@ HighAvailability::HighAvailability(PortBitSet* ports, bool) } break; } - + } s_client_map = new ClientMap; for ( int i=0; itable ) { - for (i=0; inrows; i++) + for (int i=0; inrows; i++) { - for ( node=h->table[i]; node; ) + for ( SFGHASH_NODE* node=h->table[i]; node; ) { - onode = node; + SFGHASH_NODE* onode = node; node = node->next; if ( !h->userkey && onode->key ) diff --git a/src/hash/sfhashfcn.cc b/src/hash/sfhashfcn.cc index f8051279c..57fa56275 100644 --- a/src/hash/sfhashfcn.cc +++ b/src/hash/sfhashfcn.cc @@ -165,17 +165,17 @@ void mix_str( size_t str_to_hash(const uint8_t *str, int length ) { - size_t a,b,c,tmp; - int i,j,k,m; - a = b = c = 0; - for (i = 0, j = 0; i < length; i += 4) + size_t a = 0, b = 0, c = 0; + + for (int i = 0, j = 0; i < length; i += 4) { - tmp = 0; - k = length - i; + size_t tmp = 0; + int k = length - i; + if (k > 4) k=4; - for (m = 0; m < k; m++) + for (int m = 0; m < k; m++) { tmp |= *(str + i + m) << m*8; } diff --git a/src/hash/sfxhash.cc b/src/hash/sfxhash.cc index 6e61d9ca5..62300d8b0 100644 --- a/src/hash/sfxhash.cc +++ b/src/hash/sfxhash.cc @@ -1070,7 +1070,7 @@ int main(int argc, char** argv) int i; SFXHASH* t; SFXHASH_NODE* n; - char strkey[256], strdata[256], * p; + char strkey[256], strdata[256]; int num = 100; int mem = 0; @@ -1119,9 +1119,7 @@ int main(int argc, char** argv) snprintf(strkey, sizeof(strkey) - 1, "KeyWord%5.5d",i+1); strkey[sizeof(strkey) - 1] = '\0'; - p = (char*)sfxhash_find(t, strkey); - - if (p) + if ( char* p = (char*)sfxhash_find(t, strkey) ) printf("Hash-key=%*s, data=%*s\n", strlen(strkey),strkey, strlen(strkey), p); } diff --git a/src/hash/test/sfghash_test.cc b/src/hash/test/sfghash_test.cc index 45d4ffc3b..59b952f35 100644 --- a/src/hash/test/sfghash_test.cc +++ b/src/hash/test/sfghash_test.cc @@ -58,7 +58,7 @@ TEST_GROUP(sfghash) TEST(sfghash, create_find_delete_test) { int i; - char str[256], *p; + char str[256]; int num=100; // Create a Hash Table @@ -78,7 +78,7 @@ TEST(sfghash, create_find_delete_test) snprintf(str, sizeof(str), "KeyWord%d",i+1); str[sizeof(str) - 1] = '\0'; - p = (char*)sfghash_find(t, str); + char* p = (char*)sfghash_find(t, str); CHECK(p != nullptr); CHECK(p == (void *)(str + (i+1))); @@ -98,7 +98,7 @@ TEST(sfghash, create_find_delete_test) TEST(sfghash, collision_test) { int i; - char str[256], * p; + char str[256]; int num=100; // Create a Hash Table with smaller entries @@ -126,7 +126,7 @@ TEST(sfghash, collision_test) snprintf(str, sizeof(str), "KeyWord%d",i+1); str[sizeof(str) - 1] = '\0'; - p = (char*)sfghash_find(t, str); + char* p = (char*)sfghash_find(t, str); CHECK(p != nullptr); CHECK(p == (void *)(str + (i+1))); diff --git a/src/helpers/base64_encoder.cc b/src/helpers/base64_encoder.cc index b65597d13..9b7578c5a 100644 --- a/src/helpers/base64_encoder.cc +++ b/src/helpers/base64_encoder.cc @@ -50,12 +50,12 @@ unsigned Base64Encoder::encode( const uint8_t* data = plain_text; const uint8_t* const data_end = plain_text + length; char* p = buf; - uint8_t fragment; switch (step) { while (true) { + uint8_t fragment; case step_A: if (data == data_end) { @@ -66,6 +66,7 @@ unsigned Base64Encoder::encode( state = (fragment & 0x0fc) >> 2; *p++ = b64(state); state = (fragment & 0x003) << 4; + // fallthrough case step_B: if (data == data_end) { @@ -76,6 +77,7 @@ unsigned Base64Encoder::encode( state |= (fragment & 0x0f0) >> 4; *p++ = b64(state); state = (fragment & 0x00f) << 2; + // fallthrough case step_C: if (data == data_end) { diff --git a/src/ips_options/asn1_util.cc b/src/ips_options/asn1_util.cc index 8a0cd8d7e..83de5377a 100644 --- a/src/ips_options/asn1_util.cc +++ b/src/ips_options/asn1_util.cc @@ -228,7 +228,6 @@ static int asn1_decode_tag_num_ext(ASN1_DATA* asn1_data, u_int* tag_num) static int asn1_decode_ident(ASN1_TYPE* asn1_type, ASN1_DATA* asn1_data) { ASN1_IDENT* ident; - int iRet; if (!asn1_type || !asn1_data) return ASN1_ERR_NULL_MEM; @@ -253,8 +252,7 @@ static int asn1_decode_ident(ASN1_TYPE* asn1_type, ASN1_DATA* asn1_data) { ident->tag_type = SF_ASN1_TAG_EXTENSION; - iRet = asn1_decode_tag_num_ext(asn1_data, &ident->tag); - if (iRet) + if ( asn1_decode_tag_num_ext(asn1_data, &ident->tag) ) { //printf("** decode_ident: ext_len error\n"); return ASN1_ERR_INVALID_BER_TAG_LEN; diff --git a/src/ips_options/ips_byte_test.cc b/src/ips_options/ips_byte_test.cc index a27cd93c6..6fcc1d534 100644 --- a/src/ips_options/ips_byte_test.cc +++ b/src/ips_options/ips_byte_test.cc @@ -329,7 +329,7 @@ IpsOption::EvalStatus ByteTestOption::eval(Cursor& c, Packet* p) } uint32_t value = 0; - int payload_bytes_grabbed = 0; + int payload_bytes_grabbed = 0; // FIXIT-L reduce scope if (!btd->data_string_convert_flag) { diff --git a/src/ips_options/ips_content.cc b/src/ips_options/ips_content.cc index 9ce0f10a0..69d71d373 100644 --- a/src/ips_options/ips_content.cc +++ b/src/ips_options/ips_content.cc @@ -32,6 +32,7 @@ #include "profiler/profiler.h" #include "utils/boyer_moore.h" #include "utils/util.h" +#include "utils/stats.h" #include "extract.h" @@ -121,8 +122,7 @@ public: bool is_relative() override { return config->pmd.is_relative(); } - bool retry() override - { return !config->pmd.is_negated(); } + bool retry(Cursor&) override; ContentData* get_data() { return config; } @@ -162,6 +162,23 @@ ContentOption::~ContentOption() snort_free(cd); } +bool ContentOption::retry(Cursor& c) +{ + if ( config->pmd.is_negated() ) + return false; + + if ( !config->pmd.depth ) + return true; + + // FIXIT-L consider moving adjusting delta from eval to retry + assert(c.get_delta() >= config->match_delta); + + unsigned min = c.get_delta() + config->pmd.pattern_size; + unsigned max = c.get_delta() - config->match_delta + config->pmd.offset + config->pmd.depth; + + return min <= max; +} + uint32_t ContentOption::hash() const { uint32_t a,b,c; diff --git a/src/ips_options/ips_flowbits.cc b/src/ips_options/ips_flowbits.cc index 1b701bbfc..73f3ca036 100644 --- a/src/ips_options/ips_flowbits.cc +++ b/src/ips_options/ips_flowbits.cc @@ -517,17 +517,14 @@ static IpsOption::EvalStatus check_flowbits( void FlowbitResetCounts() { - SFGHASH_NODE* n; - FLOWBITS_OBJECT* fb; - - if (flowbits_hash == nullptr) + if ( !flowbits_hash ) return; - for (n = sfghash_findfirst(flowbits_hash); + for (SFGHASH_NODE* n = sfghash_findfirst(flowbits_hash); n != nullptr; n = sfghash_findnext(flowbits_hash)) { - fb = (FLOWBITS_OBJECT*)n->data; + FLOWBITS_OBJECT* fb = (FLOWBITS_OBJECT*)n->data; fb->set = 0; fb->isset = 0; } @@ -567,7 +564,6 @@ static bool validateName(char* name) static FLOWBITS_OBJECT* getFlowBitItem(char* flowbitName, FLOWBITS_OP* flowbits) { FLOWBITS_OBJECT* flowbits_item; - int hstatus; if (!validateName(flowbitName)) { @@ -596,7 +592,7 @@ static FLOWBITS_OBJECT* getFlowBitItem(char* flowbitName, FLOWBITS_OP* flowbits) } } - hstatus = sfghash_add(flowbits_hash, flowbitName, flowbits_item); + int hstatus = sfghash_add(flowbits_hash, flowbitName, flowbits_item); if (hstatus != SFGHASH_OK) ParseError("Could not add flowbits key (%s) to hash.",flowbitName); @@ -774,7 +770,6 @@ static void validateFlowbitsSyntax(FLOWBITS_OP* flowbits) static FLOWBITS_GRP* getFlowBitGroup(char* groupName) { - int hstatus; FLOWBITS_GRP* flowbits_grp = nullptr; if (!groupName) @@ -793,7 +788,7 @@ static FLOWBITS_GRP* getFlowBitGroup(char* groupName) { // new group defined, add (bitop set later once we know size) flowbits_grp = (FLOWBITS_GRP*)snort_calloc(sizeof(*flowbits_grp)); - hstatus = sfghash_add(flowbits_grp_hash, groupName, flowbits_grp); + int hstatus = sfghash_add(flowbits_grp_hash, groupName, flowbits_grp); if (hstatus != SFGHASH_OK) ParseAbort("Could not add flowbits group (%s) to hash.\n",groupName); @@ -993,7 +988,6 @@ static void init_groups() static void FlowBitsVerify() { SFGHASH_NODE* n; - FLOWBITS_OBJECT* fb; unsigned num_flowbits = 0; unsigned unchecked = 0, unset = 0; @@ -1004,7 +998,7 @@ static void FlowBitsVerify() n != nullptr; n= sfghash_findnext(flowbits_hash)) { - fb = (FLOWBITS_OBJECT*)n->data; + FLOWBITS_OBJECT* fb = (FLOWBITS_OBJECT*)n->data; if (fb->toggle != flowbits_toggle) { diff --git a/src/ips_options/ips_pcre.cc b/src/ips_options/ips_pcre.cc index 75e4dc6ad..4bba8d898 100644 --- a/src/ips_options/ips_pcre.cc +++ b/src/ips_options/ips_pcre.cc @@ -442,7 +442,7 @@ public: { return (config->options & SNORT_PCRE_RELATIVE) != 0; } EvalStatus eval(Cursor&, Packet*) override; - bool retry() override; + bool retry(Cursor&) override; PcreData* get_data() { return config; } @@ -478,23 +478,21 @@ PcreOption::~PcreOption() uint32_t PcreOption::hash() const { - int i,j,k,l,expression_len; - uint32_t a,b,c,tmp; - const PcreData* data = config; - - expression_len = strlen(data->expression); - a = b = c = 0; + uint32_t a = 0, b = 0, c = 0; + int expression_len = strlen(config->expression); + int i, j; for (i=0,j=0; i 4) k=4; - for (l=0; lexpression + i + l) << l*8; + tmp |= *(config->expression + i + l) << l*8; } switch (j) @@ -523,7 +521,7 @@ uint32_t PcreOption::hash() const mix(a,b,c); } - a += data->options; + a += config->options; mix_str(a,b,c,get_name()); finalize(a,b,c); @@ -591,7 +589,7 @@ IpsOption::EvalStatus PcreOption::eval(Cursor& c, Packet*) // using content, but more advanced pcre won't work for the relative / // overlap case. -bool PcreOption::retry() +bool PcreOption::retry(Cursor&) { if ((config->options & (SNORT_PCRE_INVERT | SNORT_PCRE_ANCHORED))) { diff --git a/src/ips_options/ips_regex.cc b/src/ips_options/ips_regex.cc index 4a1d49915..b0073b6ea 100644 --- a/src/ips_options/ips_regex.cc +++ b/src/ips_options/ips_regex.cc @@ -94,7 +94,7 @@ public: bool is_relative() override { return config.pmd.is_relative(); } - bool retry() override; + bool retry(Cursor&) override; PatternMatchData* get_pattern(int, RuleDirection) override { return &config.pmd; } @@ -193,7 +193,7 @@ IpsOption::EvalStatus RegexOption::eval(Cursor& c, Packet*) return NO_MATCH; } -bool RegexOption::retry() +bool RegexOption::retry(Cursor&) { return !is_relative(); } diff --git a/src/ips_options/sd_credit_card.cc b/src/ips_options/sd_credit_card.cc index 0b69bff46..07a05688e 100644 --- a/src/ips_options/sd_credit_card.cc +++ b/src/ips_options/sd_credit_card.cc @@ -67,7 +67,7 @@ static inline int CheckIssuers(const uint8_t *cardnum, uint32_t buflen) */ int SdLuhnAlgorithm(const uint8_t *buf, unsigned long long buflen) { - int i, digits, alternate, sum, val; + int i, digits, alternate, sum; char cc_digits[CC_COPY_BUF_LEN]; /* Normalized CC# string */ uint32_t j; @@ -118,7 +118,7 @@ int SdLuhnAlgorithm(const uint8_t *buf, unsigned long long buflen) sum = 0; for (i = digits - 1; i >= 0; i--) { - val = cc_digits[i] - '0'; + int val = cc_digits[i] - '0'; if (alternate) { val *= 2; diff --git a/src/ips_options/test/ips_regex_test.cc b/src/ips_options/test/ips_regex_test.cc index d81dc4aee..d77796322 100644 --- a/src/ips_options/test/ips_regex_test.cc +++ b/src/ips_options/test/ips_regex_test.cc @@ -321,7 +321,7 @@ TEST(ips_regex_option, match_absolute) Cursor c(&pkt); CHECK(opt->eval(c, &pkt) == IpsOption::MATCH); CHECK(!strcmp((char*)c.start(), " stew *")); - CHECK(opt->retry()); + CHECK(opt->retry(c)); } TEST(ips_regex_option, no_match_delta) @@ -371,7 +371,7 @@ TEST(ips_regex_option_relative, no_match) CHECK(opt->is_relative()); CHECK(opt->eval(c, &pkt) == IpsOption::NO_MATCH); - CHECK(!opt->retry()); + CHECK(!opt->retry(c)); } //------------------------------------------------------------------------- diff --git a/src/log/messages.cc b/src/log/messages.cc index 227eff1a3..db00b2fa3 100644 --- a/src/log/messages.cc +++ b/src/log/messages.cc @@ -135,8 +135,6 @@ void ParseError(const char* format, ...) static void WriteLogMessage(FILE* fh, bool prefer_fh, const char* format, va_list& ap) { - char buf[STD_BUF+1]; - if ( snort_conf && !prefer_fh ) { if ( SnortConfig::log_quiet() ) @@ -144,6 +142,7 @@ static void WriteLogMessage(FILE* fh, bool prefer_fh, const char* format, va_lis if ( SnortConfig::log_syslog() ) { + char buf[STD_BUF+1]; vsnprintf(buf, STD_BUF, format, ap); buf[STD_BUF] = '\0'; syslog(LOG_DAEMON | LOG_NOTICE, "%s", buf); @@ -195,7 +194,6 @@ void LogMessage(FILE* fh, const char* format,...) */ void WarningMessage(const char* format,...) { - char buf[STD_BUF+1]; va_list ap; if ( snort_conf and SnortConfig::log_quiet() ) @@ -205,6 +203,7 @@ void WarningMessage(const char* format,...) if ( snort_conf and SnortConfig::log_syslog() ) { + char buf[STD_BUF+1]; vsnprintf(buf, STD_BUF, format, ap); buf[STD_BUF] = '\0'; syslog(LOG_DAEMON | LOG_WARNING, "%s", buf); @@ -229,13 +228,13 @@ void WarningMessage(const char* format,...) */ void ErrorMessage(const char* format,...) { - char buf[STD_BUF+1]; va_list ap; va_start(ap, format); if ( snort_conf and SnortConfig::log_syslog() ) { + char buf[STD_BUF+1]; vsnprintf(buf, STD_BUF, format, ap); buf[STD_BUF] = '\0'; syslog(LOG_CONS | LOG_DAEMON | LOG_ERR, "%s", buf); diff --git a/src/log/packet_tracer.cc b/src/log/packet_tracer.cc index 6ff2f6729..f3f39550f 100644 --- a/src/log/packet_tracer.cc +++ b/src/log/packet_tracer.cc @@ -159,7 +159,7 @@ void PacketTracer::add_header_info(Packet* p) log("%04X\n", (uint16_t)eh->ethertype()); } - if (p->ptrs.ip_api.get_src() and p->ptrs.ip_api.get_src()) + if (p->ptrs.ip_api.get_src() and p->ptrs.ip_api.get_dst()) { char sipstr[INET6_ADDRSTRLEN], dipstr[INET6_ADDRSTRLEN]; diff --git a/src/loggers/alert_sf_socket.cc b/src/loggers/alert_sf_socket.cc index f9a6aa5a0..41db8ce67 100644 --- a/src/loggers/alert_sf_socket.cc +++ b/src/loggers/alert_sf_socket.cc @@ -242,8 +242,6 @@ static void send_sar(uint8_t* data, unsigned len) static OptTreeNode* OptTreeNode_Search(uint32_t, uint32_t sid) { SFGHASH_NODE* hashNode; - OptTreeNode* otn = nullptr; - RuleTreeNode* rtn = nullptr; if (sid == 0) return nullptr; @@ -252,8 +250,8 @@ static OptTreeNode* OptTreeNode_Search(uint32_t, uint32_t sid) hashNode; hashNode = sfghash_findnext(snort_conf->otn_map)) { - otn = (OptTreeNode*)hashNode->data; - rtn = getRuntimeRtnFromOtn(otn); + OptTreeNode* otn = (OptTreeNode*)hashNode->data; + RuleTreeNode* rtn = getRuntimeRtnFromOtn(otn); if ( rtn and is_network_protocol(rtn->proto) ) { diff --git a/src/loggers/log_pcap.cc b/src/loggers/log_pcap.cc index 9982278ef..72a0adcb4 100644 --- a/src/loggers/log_pcap.cc +++ b/src/loggers/log_pcap.cc @@ -150,15 +150,14 @@ static void LogTcpdumpStream( static void TcpdumpInitLogFile(LtdConfig*, bool no_timestamp) { string file; - string filename; - char timestamp[16]; + string filename = F_NAME; context.lastTime = time(nullptr); context.log_cnt = 0; - filename += F_NAME; if(!no_timestamp) { + char timestamp[16]; snprintf(timestamp, sizeof(timestamp), ".%lu", context.lastTime); filename += timestamp; } diff --git a/src/main/snort.cc b/src/main/snort.cc index 0b7852ebf..3ba8e7226 100644 --- a/src/main/snort.cc +++ b/src/main/snort.cc @@ -893,28 +893,28 @@ DAQ_Verdict Snort::process_packet( // process (wire-only) packet verdicts here static DAQ_Verdict update_verdict(DAQ_Verdict verdict, int& inject) { - // FIXIT-M X PKT_RESIZED is a superset of PKT_MODIFIED, so this conditional is broken if ( Active::packet_was_dropped() and Active::can_block() ) { if ( verdict == DAQ_VERDICT_PASS ) verdict = DAQ_VERDICT_BLOCK; } - else if ( s_packet->packet_flags & PKT_MODIFIED ) - { - // this packet was normalized and/or has replacements - PacketManager::encode_update(s_packet); - verdict = DAQ_VERDICT_REPLACE; - } else if ( s_packet->packet_flags & PKT_RESIZED ) { - // we never increase, only trim, but - // daq doesn't support resizing wire packet + // we never increase, only trim, but daq doesn't support resizing wire packet + PacketManager::encode_update(s_packet); + if ( !SFDAQ::inject(s_packet->pkth, 0, s_packet->pkt, s_packet->pkth->pktlen) ) { inject = 1; verdict = DAQ_VERDICT_BLOCK; } } + else if ( s_packet->packet_flags & PKT_MODIFIED ) + { + // this packet was normalized and/or has replacements + PacketManager::encode_update(s_packet); + verdict = DAQ_VERDICT_REPLACE; + } else if ( (s_packet->packet_flags & PKT_IGNORE) || (s_packet->flow && s_packet->flow->get_ignore_direction( ) == SSN_DIR_BOTH) ) { diff --git a/src/managers/codec_manager.cc b/src/managers/codec_manager.cc index 251dcc8d4..be2524db2 100644 --- a/src/managers/codec_manager.cc +++ b/src/managers/codec_manager.cc @@ -143,12 +143,11 @@ void CodecManager::release_plugins() void CodecManager::instantiate(CodecApiWrapper& wrap, Module* m, SnortConfig*) { - static std::size_t codec_id = 1; - if (!wrap.init) { std::vector ids; const CodecApi* const cd_api = wrap.api; + static std::size_t codec_id = 1; if (codec_id >= s_protocols.size()) ParseError("A maximum of 256 codecs can be registered"); @@ -158,6 +157,7 @@ void CodecManager::instantiate(CodecApiWrapper& wrap, Module* m, SnortConfig*) Codec* cd = cd_api->ctor(m); cd->get_protocol_ids(ids); + for (auto id : ids) { if (s_proto_map[to_utype(id)] != 0) @@ -166,7 +166,8 @@ void CodecManager::instantiate(CodecApiWrapper& wrap, Module* m, SnortConfig*) s_protocols[s_proto_map[to_utype(id)]]->get_name(), cd->get_name(), static_cast(id), cd->get_name()); - s_proto_map[to_utype(id)] = (decltype(s_proto_map[to_utype(id)]))codec_id; // future proofing + // future proofing + s_proto_map[to_utype(id)] = (decltype(s_proto_map[to_utype(id)]))codec_id; } wrap.init = true; diff --git a/src/memory/memory_cap.cc b/src/memory/memory_cap.cc index 30a543b91..3040e3844 100644 --- a/src/memory/memory_cap.cc +++ b/src/memory/memory_cap.cc @@ -28,6 +28,7 @@ #include "log/messages.h" #include "main/snort_config.h" +#include "main/snort_types.h" #include "profiler/memory_profiler_active_context.h" #include "utils/stats.h" @@ -220,8 +221,8 @@ void MemoryCap::print() if ( s_tracker.allocations ) { LogMessage(" main thread usage: %zu\n", s_tracker.used()); - LogMessage(" allocations: %zu\n", s_tracker.allocations); - LogMessage(" deallocations: %zu\n", s_tracker.deallocations); + LogMessage(" allocations: %" PRIu64 "\n", s_tracker.allocations); + LogMessage(" deallocations: %" PRIu64 "\n", s_tracker.deallocations); LogMessage(" thread cap: %zu\n", thread_cap); LogMessage(" preemptive threshold: %zu\n", preemptive_threshold); } diff --git a/src/mime/decode_qp.cc b/src/mime/decode_qp.cc index c1d0146f3..c04bf4901 100644 --- a/src/mime/decode_qp.cc +++ b/src/mime/decode_qp.cc @@ -100,8 +100,6 @@ QPDecode::~QPDecode() int sf_qpdecode(const char* src, uint32_t slen, char* dst, uint32_t dlen, uint32_t* bytes_read, uint32_t* bytes_copied) { - char ch; - if (!src || !slen || !dst || !dlen || !bytes_read || !bytes_copied ) return -1; @@ -110,8 +108,9 @@ int sf_qpdecode(const char* src, uint32_t slen, char* dst, uint32_t dlen, uint32 while ( (*bytes_read < slen) && (*bytes_copied < dlen)) { - ch = src[*bytes_read]; + char ch = src[*bytes_read]; *bytes_read += 1; + if ( ch == '=' ) { if ( (*bytes_read < slen)) diff --git a/src/mime/decode_uu.cc b/src/mime/decode_uu.cc index c92f54b42..f3921af71 100644 --- a/src/mime/decode_uu.cc +++ b/src/mime/decode_uu.cc @@ -125,7 +125,6 @@ UUDecode::~UUDecode() int sf_uudecode(uint8_t* src, uint32_t slen, uint8_t* dst, uint32_t dlen, uint32_t* bytes_read, uint32_t* bytes_copied, bool* begin_found, bool* end_found) { - const uint8_t* sod; int sol = 1, length = 0; const uint8_t* ptr; uint8_t* end, * dptr, * dend; @@ -150,7 +149,8 @@ int sf_uudecode(uint8_t* src, uint32_t slen, uint8_t* dst, uint32_t dlen, uint32 } else { - sod = (const uint8_t*)SnortStrnStr((const char*)src, 5, "begin"); + const uint8_t* sod = (const uint8_t*)SnortStrnStr((const char*)src, 5, "begin"); + if (sod) { *begin_found = true; diff --git a/src/mime/file_mime_decode.cc b/src/mime/file_mime_decode.cc index dc7929dfe..784ebc4e8 100644 --- a/src/mime/file_mime_decode.cc +++ b/src/mime/file_mime_decode.cc @@ -47,8 +47,6 @@ void MimeDecode::clear_decode_state() void MimeDecode::process_decode_type(const char* start, int length, bool cnt_xf, MimeStats* mime_stats) { - const char* tmp = nullptr; - if (decoder) delete decoder; @@ -58,8 +56,9 @@ void MimeDecode::process_decode_type(const char* start, int length, bool cnt_xf, { if (config->get_b64_depth() > -1) { - tmp = SnortStrcasestr(start, length, "base64"); - if ( tmp != nullptr ) + const char* tmp = SnortStrcasestr(start, length, "base64"); + + if ( tmp ) { decode_type = DECODE_B64; if (mime_stats) @@ -72,8 +71,9 @@ void MimeDecode::process_decode_type(const char* start, int length, bool cnt_xf, if (config->get_qp_depth() > -1) { - tmp = SnortStrcasestr(start, length, "quoted-printable"); - if ( tmp != nullptr ) + const char* tmp = SnortStrcasestr(start, length, "quoted-printable"); + + if ( tmp ) { decode_type = DECODE_QP; if (mime_stats) @@ -86,8 +86,9 @@ void MimeDecode::process_decode_type(const char* start, int length, bool cnt_xf, if (config->get_uu_depth() > -1) { - tmp = SnortStrcasestr(start, length, "uuencode"); - if ( tmp != nullptr ) + const char* tmp = SnortStrcasestr(start, length, "uuencode"); + + if ( tmp ) { decode_type = DECODE_UU; if (mime_stats) diff --git a/src/mime/file_mime_process.cc b/src/mime/file_mime_process.cc index 5831dcd95..bee13b0db 100644 --- a/src/mime/file_mime_process.cc +++ b/src/mime/file_mime_process.cc @@ -190,7 +190,6 @@ const uint8_t* MimeSession::process_mime_header(const uint8_t* ptr, while (ptr < data_end_marker) { - int header_name_len; int max_header_name_len = 0; get_mime_eol(ptr, data_end_marker, &eol, &eolm); @@ -238,7 +237,8 @@ const uint8_t* MimeSession::process_mime_header(const uint8_t* ptr, } /* Check for Exim 4.32 exploit where number of chars before colon is greater than 64 */ - header_name_len = colon - ptr; + int header_name_len = colon - ptr; + if ((colon < eolm) && (header_name_len > MAX_HEADER_NAME_LEN)) { max_header_name_len = header_name_len; diff --git a/src/network_inspectors/appid/app_info_table.cc b/src/network_inspectors/appid/app_info_table.cc index 8609fe2e9..669adebfa 100644 --- a/src/network_inspectors/appid/app_info_table.cc +++ b/src/network_inspectors/appid/app_info_table.cc @@ -512,14 +512,16 @@ int16_t AppInfoManager::add_appid_protocol_reference(const char* protocol) void AppInfoManager::init_appid_info_table(AppIdModuleConfig* mod_config) { - char buf[MAX_TABLE_LINE_LEN]; char filepath[PATH_MAX]; - snprintf(filepath, sizeof(filepath), "%s/odp/%s", mod_config->app_detector_dir, APP_MAPPING_FILE); + FILE* tableFile = fopen(filepath, "r"); + if ( tableFile ) { + char buf[MAX_TABLE_LINE_LEN]; + while (fgets(buf, sizeof(buf), tableFile)) { AppId app_id; diff --git a/src/network_inspectors/appid/appid_config.cc b/src/network_inspectors/appid/appid_config.cc index d9a7d19ad..c3dc1906e 100644 --- a/src/network_inspectors/appid/appid_config.cc +++ b/src/network_inspectors/appid/appid_config.cc @@ -254,12 +254,9 @@ next: ; #ifdef USE_RNA_CONFIG void AppIdConfig::configure_analysis_networks(char* toklist[], uint32_t flag) { - int zone; NetworkSet* my_net_list; - RNAIpAddrSet* ias; RNAIpv6AddrSet* ias6; char* p; - long tmp; if (toklist[0]) { @@ -271,10 +268,12 @@ void AppIdConfig::configure_analysis_networks(char* toklist[], uint32_t flag) NSIPv6Addr six; char min_ip[INET6_ADDRSTRLEN]; char max_ip[INET6_ADDRSTRLEN]; + int zone; if (toklist[1]) { - tmp = strtol(toklist[1], &p, 10); + long tmp = strtol(toklist[1], &p, 10); + if (!*toklist[1] || *p != 0 || tmp >= MAX_ZONES || tmp < -1) { ErrorMessage("Invalid Analyze: %s '%s'", toklist[0], toklist[1]); @@ -324,12 +323,16 @@ void AppIdConfig::configure_analysis_networks(char* toklist[], uint32_t flag) } else { - ias = ParseIpCidr(toklist[0], app_id_netmasks); + RNAIpAddrSet* ias = ParseIpCidr(toklist[0], app_id_netmasks); + if (ias) { + int zone; + if (toklist[1]) { - tmp = strtol(toklist[1], &p, 10); + unsigned long tmp = strtol(toklist[1], &p, 10); + if (!*toklist[1] || *p != 0 || tmp >= MAX_ZONES || tmp < -1) { ErrorMessage("Invalid Analyze: %s '%s'", toklist[0], toklist[1]); @@ -413,7 +416,6 @@ void AppIdConfig::process_port_exclusion(char* toklist[]) { int i = 1; char* p; - RNAIpAddrSet* ias; RNAIpv6AddrSet* ias6; IpProtocol proto; unsigned long dir; @@ -495,7 +497,7 @@ void AppIdConfig::process_port_exclusion(char* toklist[]) } else { - ias = ParseIpCidr(toklist[i], app_id_netmasks); + RNAIpAddrSet* ias = ParseIpCidr(toklist[i], app_id_netmasks); if (!ias || ias->addr_flags) { if (ias) @@ -591,7 +593,6 @@ static int tokenize(char* data, char* toklist[]) char** ap; int argcount = 0; int i = 0; - char* tok; int drop_further = 0; for (ap = (char**)toklist; ap < &toklist[MAX_TOKS] && (*ap = strsep(&data, " ")) != nullptr; ) @@ -608,7 +609,7 @@ static int tokenize(char* data, char* toklist[]) /* scan for comments */ while (i < argcount) { - tok = toklist[i]; + char* tok = toklist[i]; if (tok[0] == '#' && !drop_further) { @@ -629,12 +630,8 @@ static int tokenize(char* data, char* toklist[]) int AppIdConfig::load_analysis_config(const char* config_file, int reload, int instance_id) { - FILE* fp; char linebuffer[MAX_LINE]; - char* cptr; char* toklist[MAX_TOKS]; - int num_toks; - unsigned line = 0; NetworkSet* my_net_list; if (NetworkSetManager::create(&net_list)) @@ -658,18 +655,20 @@ int AppIdConfig::load_analysis_config(const char* config_file, int reload, int i else { DebugFormat(DEBUG_APPID, "Loading configuration file: %s", config_file); + FILE* fp; if (!(fp = fopen(config_file, "r"))) { ErrorMessage("Unable to open %s", config_file); return -1; } + unsigned line = 0; while (fgets(linebuffer, MAX_LINE, fp) != nullptr) { line++; strip(linebuffer); - cptr = linebuffer; + char* cptr = linebuffer; while (isspace((int)*cptr)) cptr++; @@ -677,8 +676,8 @@ int AppIdConfig::load_analysis_config(const char* config_file, int reload, int i if (*cptr && (*cptr != '#') && (*cptr != 0x0a)) { memset(toklist, 0, sizeof(toklist)); - num_toks = tokenize(cptr, toklist); - if (num_toks < 2) + + if (tokenize(cptr, toklist) < 2) { fclose(fp); ErrorMessage("Invalid configuration file line %u", line); diff --git a/src/network_inspectors/appid/appid_http_session.cc b/src/network_inspectors/appid/appid_http_session.cc index 97ab80de9..01386c71d 100644 --- a/src/network_inspectors/appid/appid_http_session.cc +++ b/src/network_inspectors/appid/appid_http_session.cc @@ -371,7 +371,6 @@ void AppIdHttpSession::process_chp_buffers() int AppIdHttpSession::process_http_packet(int direction) { Profile http_profile_context(httpPerfStats); - constexpr auto RESPONSE_CODE_LENGTH = 3; AppId service_id = APP_ID_NONE; AppId client_id = APP_ID_NONE; AppId payload_id = APP_ID_NONE; @@ -391,6 +390,8 @@ int AppIdHttpSession::process_http_packet(int direction) if (response_code) { asd->set_session_flags(APPID_SESSION_RESPONSE_CODE_CHECKED); + constexpr auto RESPONSE_CODE_LENGTH = 3; + if (response_code_buflen != RESPONSE_CODE_LENGTH) { if (asd->session_logging_enabled) diff --git a/src/network_inspectors/appid/appid_utils/fw_avltree.cc b/src/network_inspectors/appid/appid_utils/fw_avltree.cc index 5a159c8d6..9694df0e3 100644 --- a/src/network_inspectors/appid/appid_utils/fw_avltree.cc +++ b/src/network_inspectors/appid/appid_utils/fw_avltree.cc @@ -409,14 +409,15 @@ FwQNode* fwAvlSerialize(FwAvlTree* tree) void fwAvlDeleteTree(FwAvlTree* tree, void (* dataDelete)(void* data)) { FwQNode* node = fwAvlSerialize(tree); - FwQNode* tmp; while (node != nullptr) { if (dataDelete) dataDelete(node->treeNode->data); + snort_free(node->treeNode); - tmp = node; + + FwQNode* tmp = node; node = node->next; snort_free(tmp); } diff --git a/src/network_inspectors/appid/appid_utils/network_set.h b/src/network_inspectors/appid/appid_utils/network_set.h index 3f062e56d..cf6d5bcda 100644 --- a/src/network_inspectors/appid/appid_utils/network_set.h +++ b/src/network_inspectors/appid/appid_utils/network_set.h @@ -245,21 +245,25 @@ public: static int contains_ex(NetworkSet* network_set, uint32_t ipaddr, unsigned* type) { int low=0; - int middle=0; int high=0; - *type = 0; + if (!network_set) return 0; + if (!network_set->count) return 0; + high = network_set->count - 1; + if (ipaddr < network_set->pnetwork[low]->range_min || ipaddr > network_set->pnetwork[high]->range_max) return 0; + while (low <= high) { - middle = low + ((high - low)>>1); + int middle = low + ((high - low)>>1); + if (ipaddr < network_set->pnetwork[middle]->range_min) high = middle - 1; else if (ipaddr > network_set->pnetwork[middle]->range_max) @@ -276,15 +280,17 @@ public: static int contains6_ex(NetworkSet* network_set, NSIPv6Addr* ipaddr, unsigned* type) { int low=0; - int middle=0; int high=0; - *type = 0; + if (!network_set) return 0; + if (!network_set->count6) return 0; + high = network_set->count6 - 1; + if (compare_ipv6_address(ipaddr, &network_set->pnetwork6[low]->range_min) < 0 || compare_ipv6_address(ipaddr, &network_set->pnetwork6[high]->range_max) > 0) { @@ -292,7 +298,8 @@ public: } while (low <= high) { - middle = low + ((high - low)>>1); + int middle = low + ((high - low)>>1); + if (compare_ipv6_address(ipaddr, &network_set->pnetwork6[middle]->range_min) < 0) high = middle - 1; else if (compare_ipv6_address(ipaddr, &network_set->pnetwork6[middle]->range_max) > 0) diff --git a/src/network_inspectors/appid/appid_utils/sf_multi_mpse.cc b/src/network_inspectors/appid/appid_utils/sf_multi_mpse.cc index ae2af094f..9cec65f48 100644 --- a/src/network_inspectors/appid/appid_utils/sf_multi_mpse.cc +++ b/src/network_inspectors/appid/appid_utils/sf_multi_mpse.cc @@ -334,7 +334,6 @@ static int addPatternRecursively(void* root, const tMlpPattern** inputPatternLis tPatternList* newNode; const tMlpPattern* nextPattern; const tMlpPattern* patterns = *inputPatternList; - int rvalue; if (!rootNode || !patterns || !patterns->pattern) return -1; @@ -343,9 +342,11 @@ static int addPatternRecursively(void* root, const tMlpPattern** inputPatternLis patternList; prevNode = patternList, patternList = patternList->nextPattern) { - rvalue = compareAppUrlPatterns(patterns, patternList); + int rvalue = compareAppUrlPatterns(patterns, patternList); + if (rvalue < 0) continue; + if (rvalue == 0) { nextPattern = *(inputPatternList+1); diff --git a/src/network_inspectors/appid/client_plugins/client_app_ssh.cc b/src/network_inspectors/appid/client_plugins/client_app_ssh.cc index 093bf2a50..424a1d453 100644 --- a/src/network_inspectors/appid/client_plugins/client_app_ssh.cc +++ b/src/network_inspectors/appid/client_plugins/client_app_ssh.cc @@ -374,11 +374,10 @@ static inline int ssh_client_sm(const uint8_t* data, uint16_t size, ClientSSHData* fd) { uint16_t offset = 0; - uint8_t d; while (offset < size) { - d = data[offset]; + uint8_t d = data[offset]; switch (fd->state) { case SSH_CLIENT_STATE_BANNER: diff --git a/src/network_inspectors/appid/detector_plugins/detector_dns.cc b/src/network_inspectors/appid/detector_plugins/detector_dns.cc index 50e3ce570..ef18273c4 100644 --- a/src/network_inspectors/appid/detector_plugins/detector_dns.cc +++ b/src/network_inspectors/appid/detector_plugins/detector_dns.cc @@ -323,16 +323,17 @@ void DnsValidator::reset_dns_info(AppIdSession* asd) int DnsValidator::dns_validate_label(const uint8_t* data, uint16_t* offset, uint16_t size, uint8_t* len, unsigned* len_valid) { - const DNSLabel* lbl; const DNSLabelPtr* lbl_ptr; const DNSLabelBitfield* lbl_bit; uint16_t tmp; *len = 0; *len_valid = 1; + while ((size > *offset) && (size-(*offset)) >= (int)offsetof(DNSLabel, name)) { - lbl = (const DNSLabel*)(data + (*offset)); + const DNSLabel* lbl = (const DNSLabel*)(data + (*offset)); + switch (lbl->len & DNS_LENGTH_FLAGS) { case 0xC0: @@ -388,19 +389,20 @@ int DnsValidator::dns_validate_query(const uint8_t* data, uint16_t* offset, uint uint8_t host_len; unsigned host_len_valid; uint16_t host_offset; - const DNSQueryFixed* query; - uint16_t record_type; host = data + *offset; host_offset = *offset; ret = dns_validate_label(data, offset, size, &host_len, &host_len_valid); + if (ret == APPID_SUCCESS) { - query = (const DNSQueryFixed*)(data + *offset); + const DNSQueryFixed* query = (const DNSQueryFixed*)(data + *offset); *offset += sizeof(DNSQueryFixed); + if (host_reporting) { - record_type = ntohs(query->QType); + uint16_t record_type = ntohs(query->QType); + if ((host_len == 0) || (!host_len_valid)) { host = nullptr; @@ -434,12 +436,8 @@ int DnsValidator::dns_validate_answer(const uint8_t* data, uint16_t* offset, uin uint16_t id, uint8_t rcode, bool host_reporting, AppIdSession* asd) { int ret; - const uint8_t* host; uint8_t host_len; unsigned host_len_valid; - uint16_t host_offset; - uint16_t record_type; - uint32_t ttl; uint16_t r_data_offset; ret = dns_validate_label(data, offset, size, &host_len, &host_len_valid); @@ -455,8 +453,9 @@ int DnsValidator::dns_validate_answer(const uint8_t* data, uint16_t* offset, uin return APPID_NOMATCH; if (host_reporting) { - record_type = ntohs(ad->type); - ttl = ntohl(ad->ttl); + uint16_t record_type = ntohs(ad->type); + uint32_t ttl = ntohl(ad->ttl); + switch (record_type) { case PATTERN_A_REC: @@ -470,16 +469,22 @@ int DnsValidator::dns_validate_answer(const uint8_t* data, uint16_t* offset, uin add_dns_response_info(asd, id, nullptr, 0, 0, rcode, ttl); break; case PATTERN_PTR_REC: - host = data + r_data_offset; - host_offset = r_data_offset; - ret = dns_validate_label(data, &r_data_offset, size, &host_len, &host_len_valid); - if ((host_len == 0) || (!host_len_valid)) { - host = nullptr; - host_len = 0; - host_offset = 0; + const uint8_t* host = data + r_data_offset; + uint16_t host_offset = r_data_offset; + + ret = dns_validate_label( + data, &r_data_offset, size, &host_len, &host_len_valid); + + if ((host_len == 0) || (!host_len_valid)) + { + host = nullptr; + host_len = 0; + host_offset = 0; + } + add_dns_response_info( + asd, id, host, host_len, host_offset, rcode, ttl); } - add_dns_response_info(asd, id, host, host_len, host_offset, rcode, ttl); break; default: break; @@ -867,19 +872,17 @@ void dns_detector_free_patterns() char* dns_parse_host(const uint8_t* host, uint8_t host_len) { - char* str; - const uint8_t* src; - char* dst; - uint8_t len; + char* str = static_cast(snort_calloc(host_len + 1)); // plus '\0' at end + const uint8_t* src = host; + char* dst = str; + uint32_t dstLen = 0; - str = static_cast(snort_calloc(host_len + 1)); // plus '\0' at end - src = host; - dst = str; while (*src != 0) { - len = *src; + uint8_t len = *src; src++; + if ((dstLen + len) <= host_len) memcpy(dst, src, len); else diff --git a/src/network_inspectors/appid/detector_plugins/detector_imap.cc b/src/network_inspectors/appid/detector_plugins/detector_imap.cc index 19aa58849..91aa4faa0 100644 --- a/src/network_inspectors/appid/detector_plugins/detector_imap.cc +++ b/src/network_inspectors/appid/detector_plugins/detector_imap.cc @@ -516,16 +516,19 @@ ImapClientDetector::~ImapClientDetector() void ImapClientDetector::do_custom_init() { - unsigned index = 0; cmd_matcher = new SearchTool("ac_full", true); if ( !tcp_patterns.empty() ) + { + unsigned index = 0; + for (auto& pat : tcp_patterns) { cmd_matcher->add(pat.pattern, pat.length, index++); if (pat.length > longest_pattern) longest_pattern = pat.length; } + } cmd_matcher->prep(); } @@ -669,7 +672,6 @@ int ImapClientDetector::validate(AppIdDiscoveryArgs& args) { char* p = fd->username; char* p_end = p + sizeof(fd->username) - 1; - int found_tick = 0; if (*s == '"') { @@ -707,6 +709,8 @@ int ImapClientDetector::validate(AppIdDiscoveryArgs& args) } else { + bool found_tick = false; + for (; s < end && p < p_end; s++) { if (isalnum(*s) || *s == '.' || *s == '@' || *s == '-' || *s == '_') @@ -718,7 +722,7 @@ int ImapClientDetector::validate(AppIdDiscoveryArgs& args) } } else if (*s == '`') - found_tick = 1; + found_tick = true; else if (*s == ' ') { fd->count++; diff --git a/src/network_inspectors/appid/detector_plugins/detector_pattern.cc b/src/network_inspectors/appid/detector_plugins/detector_pattern.cc index 60a884954..bedf7a9ab 100644 --- a/src/network_inspectors/appid/detector_plugins/detector_pattern.cc +++ b/src/network_inspectors/appid/detector_plugins/detector_pattern.cc @@ -77,11 +77,11 @@ static void read_patterns(PortPatternNode* portPatternList, PatternService** ser char* lastName = nullptr; short lastPort = 0; IpProtocol lastProto = IpProtocol::PROTO_NOT_SET; - bool newPs; for (PortPatternNode* pNode = portPatternList; pNode; pNode = pNode->next) { - newPs = false; + bool newPs = false; + if (!ps || !lastName || strcmp(lastName, pNode->detectorName) || lastProto != pNode->protocol) { diff --git a/src/network_inspectors/appid/detector_plugins/detector_pop3.cc b/src/network_inspectors/appid/detector_plugins/detector_pop3.cc index 0c4cf1fe0..8f6c02650 100644 --- a/src/network_inspectors/appid/detector_plugins/detector_pop3.cc +++ b/src/network_inspectors/appid/detector_plugins/detector_pop3.cc @@ -209,16 +209,19 @@ Pop3ClientDetector::~Pop3ClientDetector() void Pop3ClientDetector::do_custom_init() { - unsigned index = 0; cmd_matcher = new SearchTool("ac_full", true); if ( !tcp_patterns.empty() ) + { + unsigned index = 0; + for (auto& pat : tcp_patterns) { cmd_matcher->add(pat.pattern, pat.length, index++); if (pat.length > longest_pattern) longest_pattern = pat.length; } + } cmd_matcher->prep(); } diff --git a/src/network_inspectors/appid/detector_plugins/detector_smtp.cc b/src/network_inspectors/appid/detector_plugins/detector_smtp.cc index e75520731..616065ef9 100644 --- a/src/network_inspectors/appid/detector_plugins/detector_smtp.cc +++ b/src/network_inspectors/appid/detector_plugins/detector_smtp.cc @@ -798,7 +798,8 @@ int SmtpServiceDetector::validate(AppIdDiscoveryArgs& args) fd->state = SMTP_SERVICE_STATE_HELO; break; case 421: - if (service_strstr(args.data, args.size, (const uint8_t*)SMTP_CLOSING_CONN, sizeof(SMTP_CLOSING_CONN)-1)) + if (service_strstr(args.data, args.size, + (const uint8_t*)SMTP_CLOSING_CONN, sizeof(SMTP_CLOSING_CONN)-1)) goto success; case 520: case 554: diff --git a/src/network_inspectors/appid/detector_plugins/http_url_patterns.cc b/src/network_inspectors/appid/detector_plugins/http_url_patterns.cc index b07630cac..2ea04cbad 100644 --- a/src/network_inspectors/appid/detector_plugins/http_url_patterns.cc +++ b/src/network_inspectors/appid/detector_plugins/http_url_patterns.cc @@ -804,11 +804,9 @@ void HttpPatternMatchers::get_http_offsets(Packet* pkt, AppIdHttpSession* hsessi static inline void free_matched_patterns(MatchedPatterns* mp) { - MatchedPatterns* tmp; - while (mp) { - tmp = mp; + MatchedPatterns* tmp = mp; mp = mp->next; snort_free(tmp); } @@ -968,7 +966,6 @@ AppId HttpPatternMatchers::scan_chp(ChpMatchDescriptor& cmd, char** version, cha { MatchedCHPAction* insert_sweep2 = nullptr; bool inhibit_modify = false; - CHPAction* match = nullptr; AppId ret = APP_ID_NONE; unsigned pt = cmd.cur_ptype; @@ -988,9 +985,11 @@ AppId HttpPatternMatchers::scan_chp(ChpMatchDescriptor& cmd, char** version, cha for ( auto& tmp: cmd.chp_matches[pt] ) { - match = (CHPAction*)tmp.mpattern; + CHPAction* match = (CHPAction*)tmp.mpattern; + if ( match->appIdInstance > hsession->chp_candidate ) break; // because the list is sorted we know there are no more + else if ( match->appIdInstance == hsession->chp_candidate ) { switch (match->action) @@ -1456,7 +1455,6 @@ done: int HttpPatternMatchers::get_appid_by_pattern(const uint8_t* data, unsigned size, char** version) { MatchedPatterns* mp = nullptr; - char temp_ver[MAX_VERSION_SIZE]; via_matcher.find_all((const char*)data, size, &http_pattern_match, false, (void*)&mp); if (mp) @@ -1466,6 +1464,7 @@ int HttpPatternMatchers::get_appid_by_pattern(const uint8_t* data, unsigned size { case APP_ID_SQUID: { + char temp_ver[MAX_VERSION_SIZE]; const uint8_t* data_ptr = data + mp->after_match_pos; const uint8_t* end = data + size; unsigned i = 0; @@ -1505,8 +1504,6 @@ int HttpPatternMatchers::get_appid_by_pattern(const uint8_t* data, unsigned size AppId HttpPatternMatchers::scan_header_x_working_with(const uint8_t* data, uint32_t size, char** version) { - uint32_t i; - const uint8_t* end; char temp_ver[MAX_VERSION_SIZE]; temp_ver[0] = 0; @@ -1515,8 +1512,10 @@ AppId HttpPatternMatchers::scan_header_x_working_with(const uint8_t* data, uint3 && memcmp(data, HTTP_HEADER_WORKINGWITH_ASPROXY, sizeof(HTTP_HEADER_WORKINGWITH_ASPROXY) - 1) == 0) { - end = data + size; + const uint8_t* end = data + size; data += sizeof(HTTP_HEADER_WORKINGWITH_ASPROXY) - 1; + uint32_t i; + for (i = 0; data < end && i < (MAX_VERSION_SIZE - 1) && *data != ')' && isprint(*data); data++) diff --git a/src/network_inspectors/appid/lua_detector_api.cc b/src/network_inspectors/appid/lua_detector_api.cc index 31c8c845c..815695901 100644 --- a/src/network_inspectors/appid/lua_detector_api.cc +++ b/src/network_inspectors/appid/lua_detector_api.cc @@ -46,6 +46,7 @@ #include "hash/sfxhash.h" #include "log/messages.h" #include "main/snort_debug.h" +#include "main/snort_types.h" #include "profiler/profiler.h" #include "protocols/packet.h" @@ -1471,7 +1472,6 @@ static int detector_add_length_app_cache(lua_State* L) { int i; const char* str_ptr; - uint16_t length; LengthKey length_sequence; int index = 1; @@ -1527,7 +1527,8 @@ static int detector_add_length_app_cache(lua_State* L) } str_ptr++; - length = (uint16_t)atoi(str_ptr); + uint16_t length = (uint16_t)atoi(str_ptr); + if (length == 0) { ErrorMessage("LuaDetectorApi:Invalid sequence string (\"%s\")!", @@ -2421,6 +2422,10 @@ static inline bool lua_params_validator(LuaDetectorParameters& ldp, bool packet_ assert(!ldp.pkt); } +#ifdef NDEBUG + UNUSED(ldp); +#endif + return true; } diff --git a/src/network_inspectors/appid/lua_detector_module.cc b/src/network_inspectors/appid/lua_detector_module.cc index c1ac150fa..a87ada73a 100644 --- a/src/network_inspectors/appid/lua_detector_module.cc +++ b/src/network_inspectors/appid/lua_detector_module.cc @@ -405,7 +405,6 @@ void LuaDetectorManager::list_lua_detectors() { // FIXIT-L make these perf counters size_t totalMem = 0; - size_t mem; if ( allocated_detectors.empty() ) return; @@ -415,7 +414,7 @@ void LuaDetectorManager::list_lua_detectors() for ( auto& ld : allocated_detectors ) { LuaStateDescriptor* lsd = ld->validate_lua_state(false); - mem = lua_gc(lsd->my_lua_state, LUA_GCCOUNT, 0); + size_t mem = lua_gc(lsd->my_lua_state, LUA_GCCOUNT, 0); totalMem += mem; LogMessage("\tDetector %s: Lua Memory usage %zu kb\n", ld->get_name().c_str(), mem); } diff --git a/src/network_inspectors/appid/service_plugins/service_ftp.cc b/src/network_inspectors/appid/service_plugins/service_ftp.cc index fef5c59f2..20c51a14e 100644 --- a/src/network_inspectors/appid/service_plugins/service_ftp.cc +++ b/src/network_inspectors/appid/service_plugins/service_ftp.cc @@ -353,7 +353,6 @@ static int ftp_validate_reply(const uint8_t* data, uint16_t* offset, /* Look for (Vendor Version: or (Vendor Version) */ const unsigned char* end; const unsigned char* p; - const unsigned char* ven; const unsigned char* ver; end = &data[size-1]; for (p=&data[*offset]; pdata + RECORD_OFFSET; create_match_list(srv_original, size - RECORD_OFFSET); const char* end_srv_original = (const char*)pkt->data + RECORD_OFFSET + data_size; - for (processed_ans = 0; processed_ans < ans_count && data_size <= size && size > 0; + for (int processed_ans = 0; processed_ans < ans_count && data_size <= size && size > 0; processed_ans++ ) { // Call Decode Reference pointer function if referenced value instead of direct value @@ -285,7 +282,6 @@ int MdnsServiceDetector::analyze_user(AppIdSession* asd, const Packet* pkt, uint int ret_value = reference_pointer(srv_original, &resp_endptr, &start_index, data_size, &user_name_len, size); int user_index =0; - int user_printable_index =0; if (ret_value == -1) return -1; @@ -299,6 +295,7 @@ int MdnsServiceDetector::analyze_user(AppIdSession* asd, const Packet* pkt, uint } user_name_len -=user_index; + char user_name[MAX_LENGTH_SERVICE_NAME] = ""; memcpy(user_name, srv_original + start_index, user_name_len); user_name[user_name_len] = '\0'; @@ -337,7 +334,7 @@ int MdnsServiceDetector::analyze_user(AppIdSession* asd, const Packet* pkt, uint if (user_original ) { user_name_len = user_original - srv_original - start_index; - user_name_bkp = srv_original + start_index; + const char* user_name_bkp = srv_original + start_index; /* Non-Printable characters in the beginning */ while (user_index < user_name_len) @@ -348,7 +345,7 @@ int MdnsServiceDetector::analyze_user(AppIdSession* asd, const Packet* pkt, uint user_index++; } - user_printable_index = user_index; + int user_printable_index = user_index; /* Non-Printable characters in the between */ while (user_printable_index < user_name_len) @@ -361,8 +358,9 @@ int MdnsServiceDetector::analyze_user(AppIdSession* asd, const Packet* pkt, uint /* Copy the user name if available */ if (( user_name_len - user_index ) < MAX_LENGTH_SERVICE_NAME ) { - memcpy(user_name, user_name_bkp + user_index, user_name_len - - user_index); + char user_name[MAX_LENGTH_SERVICE_NAME]; + memcpy(user_name, user_name_bkp + user_index, + user_name_len - user_index); user_name[ user_name_len - user_index ] = '\0'; add_user(asd, user_name, APP_ID_MDNS, true); return 1; diff --git a/src/network_inspectors/appid/service_plugins/service_netbios.cc b/src/network_inspectors/appid/service_plugins/service_netbios.cc index 32d9035cf..fdaba58ed 100644 --- a/src/network_inspectors/appid/service_plugins/service_netbios.cc +++ b/src/network_inspectors/appid/service_plugins/service_netbios.cc @@ -288,7 +288,6 @@ static int netbios_validate_name_and_decode(const uint8_t** data, const NBNSLabelData* lbl_data; const NBNSLabelPtr* lbl_ptr; int i; - int j; if (end - *data < (int)sizeof(NBNSLabelLength)) return -1; @@ -317,7 +316,7 @@ static int netbios_validate_name_and_decode(const uint8_t** data, return -1; for (i=0; i<(NBNS_NAME_LEN/2); i++) { - j = 2 * i; + int j = 2 * i; if (lbl_data->data[j] < 'A' || lbl_data->data[j] > 'Z') return -1; name[i] = (uint8_t)(((uint8_t)(lbl_data->data[j] - 'A')) << 4); @@ -410,7 +409,6 @@ static int nbns_validate_answer(const uint8_t** data, const uint8_t* const begin const uint8_t* const end) { int ret; - uint16_t tmp; ret = netbios_validate_name(data, begin, end); if (ret) @@ -421,8 +419,10 @@ static int nbns_validate_answer(const uint8_t** data, const uint8_t* const begin const NBNSAnswerData* ad = (const NBNSAnswerData*)(*data); if (end - *data < (int)sizeof(NBNSAnswerData)) return -1; + *data += sizeof(NBNSAnswerData); - tmp = ntohs(ad->data_len); + uint16_t tmp = ntohs(ad->data_len); + if (end - *data < tmp) return -1; *data += tmp; @@ -626,7 +626,6 @@ static inline void smb_find_domain(const uint8_t* data, uint16_t size, const int char domain[NBNS_NAME_LEN+1]; unsigned pos = 0; uint16_t byte_count; - uint16_t sec_len; uint16_t wc; uint8_t unicode; uint32_t capabilities; @@ -663,7 +662,7 @@ static inline void smb_find_domain(const uint8_t* data, uint16_t size, const int { if (wc == 8) { - sec_len = LETOHS(&resp->sec_len); + uint16_t sec_len = LETOHS(&resp->sec_len); if (sec_len >= byte_count) return; data += sec_len; diff --git a/src/network_inspectors/appid/service_plugins/service_rpc.cc b/src/network_inspectors/appid/service_plugins/service_rpc.cc index b5e4530a5..13a20896b 100644 --- a/src/network_inspectors/appid/service_plugins/service_rpc.cc +++ b/src/network_inspectors/appid/service_plugins/service_rpc.cc @@ -279,14 +279,11 @@ int RpcServiceDetector::validate_packet(const uint8_t* data, uint16_t size, int { const ServiceRPCCall* call = nullptr; const ServiceRPCReply* reply = nullptr; - const ServiceRPC* rpc = nullptr; const ServiceRPCPortmap* pm = nullptr; const ServiceRPCAuth* a = nullptr; - const ServiceRPCPortmapReply* pmr = nullptr; uint32_t tmp = 0; uint32_t val = 0; const uint8_t* end = nullptr; - AppIdSession* pf = nullptr; const RPCProgram* rprog = nullptr; if (!size) @@ -301,7 +298,9 @@ int RpcServiceDetector::validate_packet(const uint8_t* data, uint16_t size, int rd->once = 1; if (size < sizeof(ServiceRPC)) return APPID_NOMATCH; - rpc = (const ServiceRPC*)data; + + const ServiceRPC* rpc = (const ServiceRPC*)data; + if (ntohl(rpc->type) == RPC_TYPE_REPLY) { asd->set_session_flags(APPID_SESSION_UDP_REVERSED); @@ -389,6 +388,8 @@ int RpcServiceDetector::validate_packet(const uint8_t* data, uint16_t size, int return APPID_INPROCESS; } *program = rd->program; + const ServiceRPCPortmapReply* pmr = nullptr; + switch (rd->program) { case RPC_PROGRAM_PORTMAP: @@ -403,7 +404,9 @@ int RpcServiceDetector::validate_packet(const uint8_t* data, uint16_t size, int 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, + + AppIdSession* pf = AppIdSession::create_future_session( + pkt, dip, 0, sip, (uint16_t)tmp, (IpProtocol)ntohl((uint32_t)rd->proto), app_id, 0, handler->get_inspector()); 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 07179fbd5..692d7284b 100644 --- a/src/network_inspectors/appid/service_plugins/service_ssl.cc +++ b/src/network_inspectors/appid/service_plugins/service_ssl.cc @@ -993,7 +993,6 @@ static int ssl_scan_patterns(SearchTool* matcher, const uint8_t* data, size_t si AppId* ClientAppId, AppId* payloadId) { MatchedSSLPatterns* mp = nullptr; - MatchedSSLPatterns* tmpMp; SSLCertPattern* best_match; if (!matcher) @@ -1019,7 +1018,7 @@ static int ssl_scan_patterns(SearchTool* matcher, const uint8_t* data, size_t si best_match = mp->mpattern; } } - tmpMp = mp; + MatchedSSLPatterns* tmpMp = mp; mp = mp->next; snort_free(tmpMp); } diff --git a/src/network_inspectors/appid/thirdparty_appid_utils.cc b/src/network_inspectors/appid/thirdparty_appid_utils.cc index 58a8ace19..f13f42226 100644 --- a/src/network_inspectors/appid/thirdparty_appid_utils.cc +++ b/src/network_inspectors/appid/thirdparty_appid_utils.cc @@ -212,15 +212,12 @@ void ThirdPartyAppIDReconfigure() void ThirdPartyAppIDFini() { - int ret; - if (thirdparty_appid_module != nullptr) { - ret = thirdparty_appid_module->fini(); + int ret = thirdparty_appid_module->fini(); + if (ret != 0) - { ErrorMessage("Could not finalize 3rd party AppID module (%d)!\n", ret); - } dlclose(module_handle); module_handle = nullptr; diff --git a/src/network_inspectors/binder/binder.cc b/src/network_inspectors/binder/binder.cc index 334e14af4..c77c41884 100644 --- a/src/network_inspectors/binder/binder.cc +++ b/src/network_inspectors/binder/binder.cc @@ -605,12 +605,11 @@ Binder::~Binder() bool Binder::configure(SnortConfig* sc) { - Binding* pb; - unsigned i, sz = bindings.size(); + unsigned sz = bindings.size(); - for ( i = 0; i < sz; i++ ) + for ( unsigned i = 0; i < sz; i++ ) { - pb = bindings[i]; + Binding* pb = bindings[i]; // Update with actual policy indices instead of user provided names if ( pb->when.ips_id ) diff --git a/src/network_inspectors/normalize/norm.cc b/src/network_inspectors/normalize/norm.cc index 6a63aa9f5..12dd42525 100644 --- a/src/network_inspectors/normalize/norm.cc +++ b/src/network_inspectors/normalize/norm.cc @@ -122,7 +122,7 @@ int Norm_Packet(NormalizerConfig* c, Packet* p) p->packet_flags |= PKT_MODIFIED; return 1; } - if ( p->packet_flags & PKT_RESIZED ) + if ( p->packet_flags & (PKT_RESIZED|PKT_MODIFIED) ) { return 1; } @@ -181,12 +181,13 @@ static int Norm_IP4( uint32_t len = p->layers[0].length + ntohs(h->ip_len); if ( (len < p->pkth->pktlen) && - ( (len >= ETH_MIN_LEN) || (p->pkth->pktlen > ETH_MIN_LEN) ) - ) + ((len >= ETH_MIN_LEN) || (p->pkth->pktlen > ETH_MIN_LEN)) ) { if ( mode == NORM_MODE_ON ) { - (const_cast(p->pkth))->pktlen = (len < ETH_MIN_LEN) ? ETH_MIN_LEN : len; + (const_cast(p->pkth))->pktlen = + (len < ETH_MIN_LEN) ? ETH_MIN_LEN : len; + p->packet_flags |= PKT_RESIZED; changes++; } diff --git a/src/network_inspectors/perf_monitor/flow_ip_tracker.cc b/src/network_inspectors/perf_monitor/flow_ip_tracker.cc index 4566b96a5..d8e024778 100644 --- a/src/network_inspectors/perf_monitor/flow_ip_tracker.cc +++ b/src/network_inspectors/perf_monitor/flow_ip_tracker.cc @@ -40,7 +40,6 @@ THREAD_LOCAL FlowIPTracker* perf_flow_ip; FlowStateValue* FlowIPTracker::find_stats(const SfIp* src_addr, const SfIp* dst_addr, int* swapped) { - SFXHASH_NODE* node; FlowStateKey key; FlowStateValue* value; @@ -60,7 +59,8 @@ FlowStateValue* FlowIPTracker::find_stats(const SfIp* src_addr, const SfIp* dst_ value = (FlowStateValue*)sfxhash_find(ip_map, &key); if (!value) { - node = sfxhash_get_node(ip_map, &key); + SFXHASH_NODE* node = sfxhash_get_node(ip_map, &key); + if (!node) { DEBUG_WRAP(DebugMessage(DEBUG_STREAM, diff --git a/src/network_inspectors/port_scan/ipobj.cc b/src/network_inspectors/port_scan/ipobj.cc index c7c13622d..e92b96a03 100644 --- a/src/network_inspectors/port_scan/ipobj.cc +++ b/src/network_inspectors/port_scan/ipobj.cc @@ -153,9 +153,6 @@ int ipset_contains(IPSET* ipc, const SfIp* ip, void* port) int ipset_print(IPSET* ipc) { - char ip_str[80]; - PORTRANGE* pr; - if ( !ipc ) return 0; @@ -168,11 +165,10 @@ int ipset_print(IPSET* ipc) p!=nullptr; p =(IP_PORT*)sflist_next(&cur_ip) ) { - SnortSnprintf(ip_str, 80, "%s", p->ip.get_addr()->ntoa()); - printf("CIDR BLOCK: %c%s", p->notflag ? '!' : ' ', ip_str); + printf("CIDR BLOCK: %c%s", p->notflag ? '!' : ' ', p->ip.get_addr()->ntoa()); SF_LNODE* cur_port; - for ( pr=(PORTRANGE*)sflist_first(&p->portset.port_list, &cur_port); + for ( PORTRANGE* pr=(PORTRANGE*)sflist_first(&p->portset.port_list, &cur_port); pr != nullptr; pr=(PORTRANGE*)sflist_next(&cur_port) ) { @@ -210,71 +206,62 @@ static int portset_add(PORTSET* portset, unsigned port_lo, unsigned port_hi) static int port_parse(char* portstr, PORTSET* portset) { - unsigned port_lo = 0, port_hi = 0; - char* port1; - char* port_begin; - char* port_end; - char* port2; - - port_begin = snort_strdup(portstr); - - port1 = port_begin; - port2 = strstr(port_begin, "-"); + char* port_begin = snort_strdup(portstr); + char* port1 = port_begin; + char* port2 = strstr(port_begin, "-"); + if (*port1 == '\0') { - if (*port1 == '\0') - { - snort_free(port_begin); - return -1; - } + snort_free(port_begin); + return -1; + } - if (port2) - { - *port2 = '\0'; - port2++; - } + if (port2) + { + *port2 = '\0'; + port2++; + } - port_lo = strtoul(port1, &port_end, 10); - if (port_end == port1) - { - snort_free(port_begin); - return -2; - } + char* port_end; + unsigned port_lo = strtoul(port1, &port_end, 10); + unsigned port_hi = 0; - if (port2) - { - port_hi = strtoul(port2, &port_end, 10); - if (port_end == port2) - { - snort_free(port_begin); - return -3; - } - } - else - { - port_hi = port_lo; - } + if (port_end == port1) + { + snort_free(port_begin); + return -2; + } - /* check to see if port is out of range */ - if ( port_hi > MAX_PORTS-1 || port_lo > MAX_PORTS-1) + if (port2) + { + port_hi = strtoul(port2, &port_end, 10); + if (port_end == port2) { snort_free(port_begin); - return -4; + return -3; } + } + else + { + port_hi = port_lo; + } - /* swap ports if necessary */ - if (port_hi < port_lo) - { - unsigned tmp; - - tmp = port_hi; - port_hi = port_lo; - port_lo = tmp; - } + /* check to see if port is out of range */ + if ( port_hi > MAX_PORTS-1 || port_lo > MAX_PORTS-1) + { + snort_free(port_begin); + return -4; + } - portset_add(portset, port_lo, port_hi); + /* swap ports if necessary */ + if (port_hi < port_lo) + { + unsigned tmp = port_hi; + port_hi = port_lo; + port_lo = tmp; } + portset_add(portset, port_lo, port_hi); snort_free(port_begin); return 0; @@ -449,7 +436,6 @@ void test_ip4_parsing() unsigned host, mask, not_flag; PORTSET portset; char** curip; - int ret; IPADDRESS* adp; char* ips[] = { @@ -469,7 +455,7 @@ void test_ip4_parsing() portset_init(&portset); /* network byte order stuff */ - if ((ret = ip4_parse(curip[0], 1, ¬_flag, &host, &mask, &portset)) != 0) + if (int ret = ip4_parse(curip[0], 1, ¬_flag, &host, &mask, &portset)) { fprintf(stderr, "Unable to parse %s with ret %d\n", curip[0], ret); } @@ -482,7 +468,7 @@ void test_ip4_parsing() } /* host byte order stuff */ - if ((ret = ip4_parse(curip[0], 0, ¬_flag, &host, &mask, &portset)) != 0) + if (int ret = ip4_parse(curip[0], 0, ¬_flag, &host, &mask, &portset)) { fprintf(stderr, "Unable to parse %s with ret %d\n", curip[0], ret); } @@ -500,7 +486,6 @@ void test_ip4_parsing() void test_ip4set_parsing() { char** curip; - int ret; char* ips[] = { "12.24.24.1/32,!24.24.24.1", @@ -521,7 +506,7 @@ void test_ip4set_parsing() IPSET* ipset = ipset_new(IPV4_FAMILY); /* network byte order stuff */ - if ((ret = ip4_setparse(ipset, curip[0])) != 0) + if (int ret = ip4_setparse(ipset, curip[0])) { ipset_free(ipset); fprintf(stderr, "Unable to parse %s with ret %d\n", curip[0], ret); diff --git a/src/network_inspectors/reputation/reputation_parse.cc b/src/network_inspectors/reputation/reputation_parse.cc index 73add8492..5f18db97a 100644 --- a/src/network_inspectors/reputation/reputation_parse.cc +++ b/src/network_inspectors/reputation/reputation_parse.cc @@ -98,11 +98,6 @@ static uint32_t estimateSizeFromEntries(uint32_t num_entries, uint32_t memcap) void IpListInit(uint32_t maxEntries, ReputationConfig* config) { - uint8_t* base; - ListInfo* whiteInfo; - ListInfo* blackInfo; - MEM_OFFSET list_ptr; - if ( !config->iplist ) { uint32_t mem_size; @@ -110,7 +105,7 @@ void IpListInit(uint32_t maxEntries, ReputationConfig* config) config->reputation_segment = (uint8_t*)snort_alloc(mem_size); segment_meminit(config->reputation_segment, mem_size); - base = config->reputation_segment; + uint8_t* base = config->reputation_segment; /*DIR_16x7_4x4 for performance, but memory usage is high *Use DIR_8x16 worst case IPV4 5K, IPV6 15K (bytes) @@ -121,7 +116,7 @@ void IpListInit(uint32_t maxEntries, ReputationConfig* config) if ( !config->iplist ) FatalError("Failed to create IP list.\n"); - list_ptr = segment_snort_calloc((size_t)DECISION_MAX, sizeof(ListInfo)); + MEM_OFFSET list_ptr = segment_snort_calloc((size_t)DECISION_MAX, sizeof(ListInfo)); if ( !list_ptr ) FatalError("Failed to create IP list.\n"); @@ -129,20 +124,21 @@ void IpListInit(uint32_t maxEntries, ReputationConfig* config) config->iplist->list_info = list_ptr; config->local_black_ptr = list_ptr + BLACKLISTED * sizeof(ListInfo); - blackInfo = (ListInfo*)&base[config->local_black_ptr]; + ListInfo* blackInfo = (ListInfo*)&base[config->local_black_ptr]; blackInfo->listType = BLACKLISTED; blackInfo->listIndex = BLACKLISTED + 1; + if (UNBLACK == config->whiteAction) { config->local_white_ptr = list_ptr + WHITELISTED_UNBLACK * sizeof(ListInfo); - whiteInfo = (ListInfo*)&base[config->local_white_ptr]; + ListInfo* whiteInfo = (ListInfo*)&base[config->local_white_ptr]; whiteInfo->listType = WHITELISTED_UNBLACK; whiteInfo->listIndex = WHITELISTED_UNBLACK + 1; } else { config->local_white_ptr = list_ptr + WHITELISTED_TRUST * sizeof(ListInfo); - whiteInfo = (ListInfo*)&base[config->local_white_ptr]; + ListInfo* whiteInfo = (ListInfo*)&base[config->local_white_ptr]; whiteInfo->listType = WHITELISTED_TRUST; whiteInfo->listIndex = WHITELISTED_TRUST + 1; } diff --git a/src/packet_io/active.cc b/src/packet_io/active.cc index 912d8824e..62c74e235 100644 --- a/src/packet_io/active.cc +++ b/src/packet_io/active.cc @@ -235,7 +235,6 @@ void Active::send_unreach(Packet* p, UnreachResponse type) bool Active::send_data( Packet* p, EncodeFlags flags, const uint8_t* buf, uint32_t blen) { - uint16_t toSend; const uint8_t* seg; uint32_t plen; @@ -258,6 +257,7 @@ bool Active::send_data( if (maxPayload) { + uint16_t toSend; do { plen = 0; diff --git a/src/packet_io/sfdaq.cc b/src/packet_io/sfdaq.cc index 7dac36224..6079fd20e 100644 --- a/src/packet_io/sfdaq.cc +++ b/src/packet_io/sfdaq.cc @@ -532,7 +532,7 @@ void SFDAQInstance::get_tunnel_capabilities() bool SFDAQInstance::get_tunnel_bypass(uint8_t proto) { - return (daq_tunnel_mask & proto ? true : false); + return (daq_tunnel_mask & proto) != 0; } bool SFDAQInstance::was_started() diff --git a/src/parser/parse_ports.cc b/src/parser/parse_ports.cc index 6263a5c6b..7c084a915 100644 --- a/src/parser/parse_ports.cc +++ b/src/parser/parse_ports.cc @@ -44,10 +44,9 @@ static int POParserInit(POParser* pop, const char* s, PortVarTable* pvTable) */ static int POPGetChar(POParser* pop) { - int c; if ( pop->slen > 0 ) { - c = pop->s[0]; + int c = pop->s[0]; pop->slen--; pop->s++; pop->pos++; @@ -260,8 +259,6 @@ static PortObject* _POParseVar(POParser* pop) static PortObject* _POParsePort(POParser* pop) { - uint16_t hport, lport; - char c; PortObject* po = PortObjectNew(); if (!po) @@ -270,10 +267,10 @@ static PortObject* _POParsePort(POParser* pop) return nullptr; } - pop->token[0]=0; + pop->token[0] = 0; /* The string in pop should only be of the form or : */ - lport = POParserGetShort(pop); + uint16_t lport = POParserGetShort(pop); if (pop->errflag) { @@ -281,12 +278,13 @@ static PortObject* _POParsePort(POParser* pop) return nullptr; } - c = POPPeekChar(pop); + char c = POPPeekChar(pop); if ( c == ':' ) /* half open range */ { POPGetChar(pop); c = POPPeekChar(pop); + uint16_t hport; if (((c == 0) && (pop->slen == 0)) || (c == ',')) diff --git a/src/parser/parse_rule.cc b/src/parser/parse_rule.cc index 7a3c0fe72..b7201eb94 100644 --- a/src/parser/parse_rule.cc +++ b/src/parser/parse_rule.cc @@ -100,8 +100,6 @@ static int FinishPortListRule( int proto, FastPatternConfig* fp) { int large_port_group = 0; - int src_cnt = 0; - int dst_cnt = 0; PortTable* dstTable; PortTable* srcTable; PortObject* aaObject; @@ -165,6 +163,9 @@ static int FinishPortListRule( if (!fp->get_single_rule_group() && (rtn->flags & (ANY_DST_PORT|ANY_SRC_PORT)) != (ANY_DST_PORT|ANY_SRC_PORT)) { + int dst_cnt = 0; + int src_cnt = 0; + if (!(rtn->flags & ANY_SRC_PORT)) { src_cnt = PortObjectPortCount(rtn->src_portobject); diff --git a/src/parser/parser.cc b/src/parser/parser.cc index bb83d3e31..2c9c5c6cd 100644 --- a/src/parser/parser.cc +++ b/src/parser/parser.cc @@ -100,7 +100,6 @@ static void CreateDefaultRules(SnortConfig* sc) static void FreeRuleTreeNodes(SnortConfig* sc) { RuleTreeNode* rtn; - OptTreeNode* otn; PolicyId policyId; SFGHASH_NODE* hashNode; @@ -111,7 +110,7 @@ static void FreeRuleTreeNodes(SnortConfig* sc) hashNode; hashNode = sfghash_findnext(sc->otn_map)) { - otn = (OptTreeNode*)hashNode->data; + OptTreeNode* otn = (OptTreeNode*)hashNode->data; /* Autogenerated OTNs along with their respective pseudo RTN * will get cleaned up when the OTN is freed */ @@ -471,7 +470,6 @@ SnortConfig* ParseSnortConf(const SnortConfig* boot_conf, const char* fname) void FreeRuleTreeNode(RuleTreeNode* rtn) { - RuleFpList* idx, * tmp; if (!rtn) return; @@ -485,10 +483,11 @@ void FreeRuleTreeNode(RuleTreeNode* rtn) sfvar_free(rtn->dip); } - idx = rtn->rule_func; + RuleFpList* idx = rtn->rule_func; + while (idx) { - tmp = idx; + RuleFpList* tmp = idx; idx = idx->next; snort_free(tmp); } @@ -686,7 +685,6 @@ void OrderRuleLists(SnortConfig* sc, const char* order) int i; int evalIndex = 0; RuleListNode* ordered_list = nullptr; - RuleListNode* prev; RuleListNode* node; char** toks; int num_toks; @@ -695,7 +693,7 @@ void OrderRuleLists(SnortConfig* sc, const char* order) for ( i = 0; i < num_toks; i++ ) { - prev = nullptr; + RuleListNode* prev = nullptr; node = sc->rule_lists; while (node != nullptr) @@ -753,12 +751,10 @@ void OrderRuleLists(SnortConfig* sc, const char* order) */ RuleTreeNode* deleteRtnFromOtn(OptTreeNode* otn, PolicyId policyId, SnortConfig* sc, bool remove) { - RuleTreeNode* rtn = nullptr; - if (otn->proto_nodes && (otn->proto_node_num >= (policyId+1))) { - rtn = getRtnFromOtn(otn, policyId); + RuleTreeNode* rtn = getRtnFromOtn(otn, policyId); otn->proto_nodes[policyId] = nullptr; if ( remove && rtn ) diff --git a/src/parser/vars.cc b/src/parser/vars.cc index ed7716ee6..4609fd059 100644 --- a/src/parser/vars.cc +++ b/src/parser/vars.cc @@ -701,9 +701,6 @@ const char* ExpandVars(SnortConfig* sc, const char* string) static char estring[ 65536 ]; // FIXIT-L convert this foo to a std::string char rawvarname[128], varname[128], varaux[128], varbuffer[128]; - char varmodifier; - const char* varcontents; - int varname_completed, c, i, j, iv, jv, l_string, name_only; int quote_toggle = 0; if (!string || !*string || !strchr(string, '$')) @@ -711,13 +708,13 @@ const char* ExpandVars(SnortConfig* sc, const char* string) memset((char*)estring, 0, sizeof(estring)); - i = j = 0; - l_string = strlen(string); + int i = 0, j = 0; + int l_string = strlen(string); DebugFormat(DEBUG_CONFIGRULES, "ExpandVars, Before: %s\n", string); while (i < l_string && j < (int)sizeof(estring) - 1) { - c = string[i++]; + int c = string[i++]; if (c == '"') { @@ -729,10 +726,10 @@ const char* ExpandVars(SnortConfig* sc, const char* string) if (c == '$' && !quote_toggle) { memset((char*)rawvarname, 0, sizeof(rawvarname)); - varname_completed = 0; - name_only = 1; - iv = i; - jv = 0; + int varname_completed = 0; + int name_only = 1; + int iv = i; + int jv = 0; if (string[i] == '(') { @@ -762,17 +759,15 @@ const char* ExpandVars(SnortConfig* sc, const char* string) if (varname_completed || iv == l_string) { - char* p; - i = iv; - - varcontents = nullptr; + const char* varcontents = nullptr; memset((char*)varname, 0, sizeof(varname)); memset((char*)varaux, 0, sizeof(varaux)); - varmodifier = ' '; + char varmodifier = ' '; + + char* p = strchr(rawvarname, ':'); - p = strchr(rawvarname, ':'); if (p) { SnortStrncpy(varname, rawvarname, p - rawvarname); diff --git a/src/ports/port_object.cc b/src/ports/port_object.cc index 597617f2a..34312bdf5 100644 --- a/src/ports/port_object.cc +++ b/src/ports/port_object.cc @@ -204,13 +204,9 @@ int PortObjectAddPortAny(PortObject* po) */ PortObject* PortObjectDup(PortObject* po) { - PortObjectItem* poi = nullptr; - PortObjectItem* poinew = nullptr; SF_LNODE* lpos = nullptr; - int* prid = nullptr; - int* prule = nullptr; - PortObject* ponew = PortObjectNew(); + if ( !ponew ) return nullptr; @@ -223,11 +219,12 @@ PortObject* PortObjectDup(PortObject* po) /* Dup the Item List */ if ( po->item_list ) { - for (poi =(PortObjectItem*)sflist_first(po->item_list,&lpos); + for (PortObjectItem* poi =(PortObjectItem*)sflist_first(po->item_list,&lpos); poi != nullptr; poi =(PortObjectItem*)sflist_next(&lpos) ) { - poinew = PortObjectItemDup(poi); + PortObjectItem* poinew = PortObjectItemDup(poi); + if (!poinew) { PortObjectFree(ponew); @@ -241,11 +238,11 @@ PortObject* PortObjectDup(PortObject* po) /* Dup the input rule list */ if ( po->rule_list ) { - for (prid = (int*)sflist_first(po->rule_list,&lpos); + for (int* prid = (int*)sflist_first(po->rule_list,&lpos); prid != nullptr; prid = (int*)sflist_next(&lpos) ) { - prule = (int*)snort_calloc(sizeof(int)); + int* prule = (int*)snort_calloc(sizeof(int)); *prule = *prid; sflist_add_tail(ponew->rule_list,prule); } @@ -259,11 +256,9 @@ PortObject* PortObjectDup(PortObject* po) */ PortObject* PortObjectDupPorts(PortObject* po) { - PortObjectItem* poi = nullptr; - PortObjectItem* poinew = nullptr; SF_LNODE* lpos = nullptr; - PortObject* ponew = PortObjectNew(); + if ( !ponew ) return nullptr; @@ -276,11 +271,12 @@ PortObject* PortObjectDupPorts(PortObject* po) /* Dup the Item List */ if ( po->item_list ) { - for (poi =(PortObjectItem*)sflist_first(po->item_list,&lpos); + for (PortObjectItem* poi =(PortObjectItem*)sflist_first(po->item_list,&lpos); poi != nullptr; poi =(PortObjectItem*)sflist_next(&lpos) ) { - poinew = PortObjectItemDup(poi); + PortObjectItem* poinew = PortObjectItemDup(poi); + if (!poinew) { PortObjectFree(ponew); @@ -357,22 +353,20 @@ int PortObjectEqual(PortObject* a, PortObject* b) */ int PortObjectPortCount(PortObject* po) { - PortObjectItem* poi; SF_LNODE* cursor; int cnt=0; - int nports; if ( !po ) return 0; - for (poi=(PortObjectItem*)sflist_first(po->item_list, &cursor); + for (PortObjectItem* poi=(PortObjectItem*)sflist_first(po->item_list, &cursor); poi != nullptr; poi=(PortObjectItem*)sflist_next(&cursor) ) { if ( poi->any() ) return -1; - nports = poi->hport - poi->lport + 1; + int nports = poi->hport - poi->lport + 1; if ( poi->negate ) cnt -= nports; @@ -509,15 +503,13 @@ int PortObjectRemovePorts(PortObject* a, PortObject* b) */ PortObject* PortObjectAppend(PortObject* poa, PortObject* pob) { - PortObjectItem* poia; - PortObjectItem* poib; SF_LNODE* cursor; - for ( poib = (PortObjectItem*)sflist_first(pob->item_list, &cursor); + for ( PortObjectItem* poib = (PortObjectItem*)sflist_first(pob->item_list, &cursor); poib!= nullptr; poib = (PortObjectItem*)sflist_next(&cursor) ) { - poia = PortObjectItemNew(); + PortObjectItem* poia = PortObjectItemNew(); if (!poia) return nullptr; diff --git a/src/ports/port_object2.cc b/src/ports/port_object2.cc index 82245bb2b..8784cf670 100644 --- a/src/ports/port_object2.cc +++ b/src/ports/port_object2.cc @@ -72,31 +72,20 @@ static unsigned po_rule_hash_func(SFHASHFCN* p, const unsigned char* k, int n) static int* RuleHashToSortedArray(SFGHASH* rh) { - int* prid; - int* ra; - int k = 0; - SFGHASH_NODE* node; - - if ( !rh ) - return nullptr; - - if (!rh->count) + if ( !rh or !rh->count ) return nullptr; - ra = (int*)snort_calloc(rh->count, sizeof(int)); + int* ra = (int*)snort_calloc(rh->count, sizeof(int)); + int k = 0; - for ( node = sfghash_findfirst(rh); + for ( SFGHASH_NODE* node = sfghash_findfirst(rh); node != nullptr && k < (int)rh->count; node = sfghash_findnext(rh) ) { - prid = (int*)node->data; - if ( prid ) - { + if ( int* prid = (int*)node->data ) ra[k++] = *prid; - } } - /* sort the array */ qsort(ra,rh->count,sizeof(int),integer_compare); return ra; @@ -254,21 +243,17 @@ void PortObject2Iterate(PortObject2* po, PortObjectIterator f, void* pv) /* Dup and append rule list numbers from pob to poa */ PortObject2* PortObject2AppendPortObject(PortObject2* poa, PortObject* pob) { - int* prid; - int* prid2; SF_LNODE* lpos; - for ( prid = (int*)sflist_first(pob->rule_list,&lpos); + for ( int* prid = (int*)sflist_first(pob->rule_list,&lpos); prid!= nullptr; prid = (int*)sflist_next(&lpos) ) { - prid2 = (int*)snort_calloc(sizeof(int)); + int* prid2 = (int*)snort_calloc(sizeof(int)); *prid2 = *prid; if ( sfghash_add(poa->rule_hash,prid2,prid2) != SFGHASH_OK ) - { snort_free(prid2); - } } return poa; } @@ -276,25 +261,20 @@ PortObject2* PortObject2AppendPortObject(PortObject2* poa, PortObject* pob) /* Dup and append rule list numbers from pob to poa */ PortObject2* PortObject2AppendPortObject2(PortObject2* poa, PortObject2* pob) { - int* prid; - int* prid2; - SFGHASH_NODE* node; - - for ( node = sfghash_findfirst(pob->rule_hash); + for (SFGHASH_NODE* node = sfghash_findfirst(pob->rule_hash); node!= nullptr; node = sfghash_findnext(pob->rule_hash) ) { - prid = (int*)node->data; + int* prid = (int*)node->data; + if ( !prid ) continue; - prid2 = (int*)snort_calloc(sizeof(int)); + int* prid2 = (int*)snort_calloc(sizeof(int)); *prid2 = *prid; if ( sfghash_add(poa->rule_hash,prid2,prid2) != SFGHASH_OK ) - { snort_free(prid2); - } } return poa; } diff --git a/src/ports/port_table.cc b/src/ports/port_table.cc index abfa00ef5..8f1361333 100644 --- a/src/ports/port_table.cc +++ b/src/ports/port_table.cc @@ -911,13 +911,12 @@ void PortTableFree(PortTable* p) } if (p->pt_mpo_hash) { - PortObject2* po; for ( SFGHASH_NODE* node = sfghash_findfirst(p->pt_mpo_hash); node; node = sfghash_findnext(p->pt_mpo_hash) ) { - po = (PortObject2*)node->data; + PortObject2* po = (PortObject2*)node->data; PortObject2Free(po); } sfghash_delete(p->pt_mpo_hash); diff --git a/src/profiler/profiler_nodes.cc b/src/profiler/profiler_nodes.cc index 321e4d616..8d267150b 100644 --- a/src/profiler/profiler_nodes.cc +++ b/src/profiler/profiler_nodes.cc @@ -152,8 +152,8 @@ ProfilerNode& ProfilerNodeMap::get_node(const std::string& key) #ifdef UNIT_TEST -static ProfileStats* s_profiler_stats; -static const char* s_profiler_name; +static ProfileStats* s_profiler_stats = nullptr; +static const char* s_profiler_name = nullptr; static ProfileStats* s_profiler_stats_getter(const char* name) { @@ -245,6 +245,8 @@ TEST_CASE( "get profile functor for function", "[profiler]" ) GetProfileFromFunction functor("foo", s_profiler_stats_getter); CHECK( functor() == &the_stats ); + + s_profiler_stats = nullptr; } TEST_CASE( "profiler node", "[profiler]" ) @@ -279,6 +281,7 @@ TEST_CASE( "profiler node", "[profiler]" ) f_node.set(s_profiler_stats_getter); f_node.accumulate(); CHECK( f_node.get_stats() == the_stats ); + s_profiler_stats = nullptr; } } diff --git a/src/protocols/packet.h b/src/protocols/packet.h index 368cf913c..b73942422 100644 --- a/src/protocols/packet.h +++ b/src/protocols/packet.h @@ -55,7 +55,7 @@ #define PKT_PSEUDO 0x00020000 /* is a pseudo packet */ #define PKT_MODIFIED 0x00040000 /* packet had normalizations, etc. */ -#define PKT_RESIZED 0x000c0000 /* packet has new size; must set modified too */ +#define PKT_RESIZED 0x00080000 /* packet has new size */ // neither of these flags will be set for (full) retransmissions or non-data segments // a partial overlap results in out of sequence condition diff --git a/src/protocols/packet_manager.cc b/src/protocols/packet_manager.cc index 9ab31e9ba..3c6012a25 100644 --- a/src/protocols/packet_manager.cc +++ b/src/protocols/packet_manager.cc @@ -760,9 +760,8 @@ int PacketManager::encode_format( // checking each time if needed. //------------------------------------------------------------------------- -static inline void add_flag(UpdateFlags& flags, - UpdateFlags flag_to_add, - const Packet* const p, +static inline void add_flag( + UpdateFlags& flags, UpdateFlags flag_to_add, const Packet* const p, decltype(Packet::packet_flags)pkt_flag) // future proofing. { if ( p->packet_flags & pkt_flag ) @@ -810,11 +809,7 @@ void PacketManager::encode_update(Packet* p) } // see IP6_Update() for an explanation of this ... - // FIXIT-L is this second statement really necessary? - // PKT_RESIZED include PKT_MODIFIED ... so get rid of that extra flag - if ( !(p->packet_flags & PKT_MODIFIED) - || (p->packet_flags & (PKT_RESIZED & ~PKT_MODIFIED)) - ) + if ( !(p->packet_flags & PKT_MODIFIED) || (p->packet_flags & PKT_RESIZED) ) { DAQ_PktHdr_t* pkth = const_cast(p->pkth); pkth->caplen = len; diff --git a/src/protocols/ssl.cc b/src/protocols/ssl.cc index 5338ed53a..00dc1eea7 100644 --- a/src/protocols/ssl.cc +++ b/src/protocols/ssl.cc @@ -130,9 +130,7 @@ static uint32_t SSL_decode_version_v3(uint8_t major, uint8_t minor) static uint32_t SSL_decode_handshake_v3(const uint8_t* pkt, int size, uint32_t cur_flags, uint32_t pkt_flags) { - const SSL_handshake_t* handshake; const SSL_handshake_hello_t* hello; - uint32_t hs_len; uint32_t retval = 0; while (size > 0) @@ -145,7 +143,7 @@ static uint32_t SSL_decode_handshake_v3(const uint8_t* pkt, int size, /* Note, handhshake version field is optional depending on type Will recast to different type as necessary. */ - handshake = (const SSL_handshake_t*)pkt; + const SSL_handshake_t* handshake = (const SSL_handshake_t*)pkt; pkt += SSL_HS_PAYLOAD_OFFSET; size -= SSL_HS_PAYLOAD_OFFSET; @@ -154,7 +152,7 @@ static uint32_t SSL_decode_handshake_v3(const uint8_t* pkt, int size, * memcpy(&hs_len, handshake->length, 3); * hs_len = ntohl(hs_len); * It was written this way for performance */ - hs_len = THREE_BYTE_LEN(handshake->length); + uint32_t hs_len = THREE_BYTE_LEN(handshake->length); switch (handshake->type) { @@ -257,9 +255,7 @@ static uint32_t SSL_decode_handshake_v3(const uint8_t* pkt, int size, static uint32_t SSL_decode_v3(const uint8_t* pkt, int size, uint32_t pkt_flags, uint8_t* alert_flags, uint16_t* partial_rec_len, int max_hb_len) { - const SSL_record_t* record; uint32_t retval = 0; - uint16_t reclen; uint16_t hblen; int ccs = 0; /* Set if we see a Change Cipher Spec and reset after the next record */ const SSL_heartbeat* heartbeat; @@ -289,13 +285,13 @@ static uint32_t SSL_decode_v3(const uint8_t* pkt, int size, uint32_t pkt_flags, break; } - record = (const SSL_record_t*)pkt; + const SSL_record_t* record = (const SSL_record_t*)pkt; pkt += SSL_REC_PAYLOAD_OFFSET; size -= SSL_REC_PAYLOAD_OFFSET; retval |= SSL_decode_version_v3(record->major, record->minor); - reclen = ntohs(record->length); + uint16_t reclen = ntohs(record->length); psize = (size < reclen) ? (reclen - size) : 0; @@ -403,7 +399,6 @@ static inline bool SSL_v3_back_compat_v2(const SSLv2_chello_t* chello) static uint32_t SSL_decode_v2(const uint8_t* pkt, int size, uint32_t pkt_flags) { - uint16_t reclen; const SSLv2_chello_t* chello; const SSLv2_shello_t* shello; uint32_t retval = 0; @@ -419,7 +414,7 @@ static uint32_t SSL_decode_v2(const uint8_t* pkt, int size, uint32_t pkt_flags) /* Note: top bit has special meaning and is not included * with the length */ - reclen = ntohs(record->length) & 0x7fff; + uint16_t reclen = ntohs(record->length) & 0x7fff; switch (record->type) { @@ -489,10 +484,6 @@ uint32_t SSL_decode( const uint8_t* pkt, int size, uint32_t pkt_flags, uint32_t prev_flags, uint8_t* alert_flags, uint16_t* partial_rec_len, int max_hb_len) { - const SSL_record_t* record; - uint16_t reclen; - uint32_t datalen; - if (!pkt || !size) return SSL_ARG_ERROR_FLAG; @@ -528,10 +519,10 @@ uint32_t SSL_decode( /* Saw a TLS version, but this could also be an SSHv2 length. * If it is, check if a hypothetical TLS record-data length agrees * with its record length */ - datalen = THREE_BYTE_LEN( (pkt+6) ); + uint32_t datalen = THREE_BYTE_LEN( (pkt+6) ); - record = (const SSL_record_t*)pkt; - reclen = ntohs(record->length); + const SSL_record_t* record = (const SSL_record_t*)pkt; + uint16_t reclen = ntohs(record->length); /* If these lengths match, it's v3 Otherwise, it's v2 */ @@ -547,10 +538,10 @@ uint32_t SSL_decode( /* A version of '2' at byte 7 overlaps with TLS record-data length. * Check if a hypothetical TLS record-data length agrees with its * record length */ - datalen = THREE_BYTE_LEN( (pkt+6) ); + uint32_t datalen = THREE_BYTE_LEN( (pkt+6) ); - record = (const SSL_record_t*)pkt; - reclen = ntohs(record->length); + const SSL_record_t* record = (const SSL_record_t*)pkt; + uint16_t reclen = ntohs(record->length); /* If these lengths match, it's v3 Otherwise, it's v2 */ diff --git a/src/search_engines/acsmx.cc b/src/search_engines/acsmx.cc index d9a7fc945..87dd10af1 100644 --- a/src/search_engines/acsmx.cc +++ b/src/search_engines/acsmx.cc @@ -139,17 +139,16 @@ static void AddMatchListEntry(ACSM_STRUCT* acsm, int state, ACSM_PATTERN* px) */ static void AddPatternStates(ACSM_STRUCT* acsm, ACSM_PATTERN* p) { - uint8_t* pattern; - int state=0, next, n; - n = p->n; - pattern = p->patrn; + int state = 0; + int n = p->n; + uint8_t* pattern = p->patrn; /* * Match up pattern with existing states */ for (; n > 0; pattern++, n--) { - next = acsm->acsmStateTable[state].NextState[*pattern]; + int next = acsm->acsmStateTable[state].NextState[*pattern]; if (next == ACSM_FAIL_STATE) break; state = next; @@ -196,13 +195,13 @@ static void Build_NFA(ACSM_STRUCT* acsm) /* Find Final States for any Failure */ for (int i = 0; i < ALPHABET_SIZE; i++) { - int next; int s = acsm->acsmStateTable[r].NextState[i]; if ( s != ACSM_FAIL_STATE ) { queue.push_back(s); int fs = acsm->acsmStateTable[r].FailState; + int next; /* * Locate the next valid state for 'i' starting at s diff --git a/src/search_engines/acsmx2.cc b/src/search_engines/acsmx2.cc index 7796492c4..d13af4ed9 100644 --- a/src/search_engines/acsmx2.cc +++ b/src/search_engines/acsmx2.cc @@ -595,23 +595,20 @@ static void AddMatchListEntry(ACSM_STRUCT2* acsm, int state, ACSM_PATTERN2* px) static void AddPatternStates(ACSM_STRUCT2* acsm, ACSM_PATTERN2* p) { - int state, next, n; - uint8_t* pattern; - - n = p->n; - pattern = p->patrn; - state = 0; + int state = 0; + int n = p->n; + uint8_t* pattern = p->patrn; /* * Match up pattern with existing states */ for (; n > 0; pattern++, n--) { - next = List_GetNextState(acsm,state,*pattern); + int next = List_GetNextState(acsm,state,*pattern); + if ((acstate_t)next == ACSM_FAIL_STATE2 || next == 0) - { break; - } + state = next; } @@ -666,7 +663,6 @@ static void Build_NFA(ACSM_STRUCT2* acsm) /* Find Final States for any Failure */ for (int i = 0; i < acsm->acsmAlphabetSize; i++) { - int next; int s = List_GetNextState(acsm,r,i); if ( (acstate_t)s != ACSM_FAIL_STATE2 ) @@ -677,6 +673,7 @@ static void Build_NFA(ACSM_STRUCT2* acsm) queue_array[s] = true; } int fs = FailState[r]; + int next; /* * Locate the next valid state for 'i' starting at fs @@ -857,21 +854,20 @@ static int Conv_List_To_Full(ACSM_STRUCT2* acsm) */ static int Conv_Full_DFA_To_Sparse(ACSM_STRUCT2* acsm) { - int cnt, m, k, i; - acstate_t* p, state; + acstate_t* p; acstate_t** NextState = acsm->acsmNextState; - acstate_t full[MAX_ALPHABET_SIZE]; - for (k=0; kacsmNumStates; k++) + for (int k=0; kacsmNumStates; k++) { - cnt=0; + int cnt=0; + acstate_t full[MAX_ALPHABET_SIZE]; memset(full, 0, acsm->sizeofstate * acsm->acsmAlphabetSize); List_ConvToFull(acsm, (acstate_t)k, full); - for (i = 0; i < acsm->acsmAlphabetSize; i++) + for (int i = 0; i < acsm->acsmAlphabetSize; i++) { - state = full[i]; + acstate_t state = full[i]; if ( state != 0 && state != ACSM_FAIL_STATE2 ) cnt++; } @@ -894,14 +890,14 @@ static int Conv_Full_DFA_To_Sparse(ACSM_STRUCT2* acsm) if (!p) return -1; - m = 0; + int m = 0; p[m++] = ACF_SPARSE; p[m++] = 0; /* no matches */ p[m++] = cnt; - for (i = 0; i < acsm->acsmAlphabetSize; i++) + for (int i = 0; i < acsm->acsmAlphabetSize; i++) { - state = full[i]; + acstate_t state = full[i]; if ( state != 0 && state != ACSM_FAIL_STATE2 ) { p[m++] = i; @@ -928,22 +924,20 @@ static int Conv_Full_DFA_To_Sparse(ACSM_STRUCT2* acsm) */ static int Conv_Full_DFA_To_Banded(ACSM_STRUCT2* acsm) { - int first = -1, last; - acstate_t* p, state, full[MAX_ALPHABET_SIZE]; + acstate_t* p, full[MAX_ALPHABET_SIZE]; acstate_t** NextState = acsm->acsmNextState; - int cnt,m,k,i; - for (k=0; kacsmNumStates; k++) + for (int k=0; kacsmNumStates; k++) { memset(full, 0, acsm->sizeofstate * acsm->acsmAlphabetSize); List_ConvToFull(acsm, (acstate_t)k, full); - first=-1; - last =-2; + int first=-1; + int last =-2; - for (i = 0; i < acsm->acsmAlphabetSize; i++) + for (int i = 0; i < acsm->acsmAlphabetSize; i++) { - state = full[i]; + acstate_t state = full[i]; if ( state !=0 && state != ACSM_FAIL_STATE2 ) { @@ -954,20 +948,20 @@ static int Conv_Full_DFA_To_Banded(ACSM_STRUCT2* acsm) } /* calc band width */ - cnt= last - first + 1; + int cnt= last - first + 1; p = (acstate_t*)AC_MALLOC_DFA(sizeof(acstate_t)*(4+cnt), sizeof(acstate_t)); if (!p) return -1; - m = 0; + int m = 0; p[m++] = ACF_BANDED; p[m++] = 0; /* no matches */ p[m++] = cnt; p[m++] = first; - for (i = first; i <= last; i++) + for (int i = first; i <= last; i++) { p[m++] = full[i]; } @@ -994,17 +988,17 @@ static int Conv_Full_DFA_To_Banded(ACSM_STRUCT2* acsm) */ static int calcSparseBands(const acstate_t* next, int* begin, int* end, int asize, int zmax) { - int i, nbands,zcnt,last=0; - acstate_t state; + int last=0; + int nbands = 0; - nbands=0; - for ( i=0; iacsmNextState; - int cnt,m,k,i,zcnt=acsm->acsmSparseMaxZcnt; - + int zcnt=acsm->acsmSparseMaxZcnt; int band_begin[MAX_ALPHABET_SIZE]; int band_end[MAX_ALPHABET_SIZE]; - int nbands,j; - acstate_t full[MAX_ALPHABET_SIZE]; - for (k=0; kacsmNumStates; k++) + for (int k=0; kacsmNumStates; k++) { + acstate_t full[MAX_ALPHABET_SIZE]; memset(full, 0, acsm->sizeofstate * acsm->acsmAlphabetSize); List_ConvToFull(acsm, (acstate_t)k, full); - nbands = calcSparseBands(full, band_begin, band_end, acsm->acsmAlphabetSize, zcnt); + int nbands = calcSparseBands(full, band_begin, band_end, acsm->acsmAlphabetSize, zcnt); /* calc band width space*/ - cnt = 3; - for (i=0; i= MAX_ALPHABET_SIZE) { @@ -1388,12 +1380,7 @@ int acsmCompile2( */ static inline acstate_t get_next_state_nfa(acstate_t* ps, acstate_t state, unsigned input) { - acstate_t fmt; - acstate_t n; - unsigned int index; - int nb; - - fmt = *ps++; + acstate_t fmt = *ps++; ps++; /* skip bMatchState */ @@ -1401,8 +1388,8 @@ static inline acstate_t get_next_state_nfa(acstate_t* ps, acstate_t state, unsig { case ACF_BANDED: { - n = ps[0]; - index = ps[1]; + acstate_t n = ps[0]; + unsigned index = ps[1]; if ( input < index ) { @@ -1439,7 +1426,7 @@ static inline acstate_t get_next_state_nfa(acstate_t* ps, acstate_t state, unsig case ACF_SPARSE: { - n = *ps++; /* number of sparse index-value entries */ + acstate_t n = *ps++; /* number of sparse index-value entries */ for (; n>0; n-- ) { @@ -1463,12 +1450,12 @@ static inline acstate_t get_next_state_nfa(acstate_t* ps, acstate_t state, unsig case ACF_SPARSE_BANDS: { - nb = *ps++; /* number of bands */ + int nb = *ps++; /* number of bands */ while ( nb > 0 ) /* for each band */ { - n = *ps++; /* number of elements */ - index = *ps++; /* 1st element value */ + acstate_t n = *ps++; /* number of elements */ + unsigned index = *ps++; /* 1st element value */ if ( input < index ) { @@ -1524,9 +1511,6 @@ static inline acstate_t get_next_state_nfa(acstate_t* ps, acstate_t state, unsig static inline acstate_t SparseGetNextStateDFA( acstate_t* ps, acstate_t, unsigned input) { - acstate_t n, nb; - unsigned int index; - switch ( ps[0] ) { case ACF_FULL: @@ -1536,7 +1520,7 @@ static inline acstate_t SparseGetNextStateDFA( case ACF_SPARSE: { - n = ps[2]; /* number of entries/ key+next pairs */ + acstate_t n = ps[2]; /* number of entries/ key+next pairs */ ps += 3; for (; n>0; n-- ) @@ -1557,14 +1541,15 @@ static inline acstate_t SparseGetNextStateDFA( case ACF_SPARSE_BANDS: { - nb = ps[2]; /* number of bands */ + acstate_t nb = ps[2]; /* number of bands */ ps += 3; while ( nb > 0 ) /* for each band */ { - n = ps[0]; /* number of elements in this band */ - index = ps[1]; /* start index/char of this band */ + acstate_t n = ps[0]; /* number of elements in this band */ + unsigned index = ps[1]; /* start index/char of this band */ + if ( input < index ) { return (acstate_t)0; @@ -1859,32 +1844,25 @@ int acsm_search_dfa_banded( ACSM_STRUCT2* acsm, const uint8_t* Tx, int n, MpseMatch match, void* context, int* current_state) { - acstate_t state; - const uint8_t* Tend; - const uint8_t* T; - int sindex; - int index; acstate_t** NextState = acsm->acsmNextState; ACSM_PATTERN2** MatchList = acsm->acsmMatchList; ACSM_PATTERN2* mlist; - acstate_t* ps; int nfound = 0; - T = Tx; - Tend = T + n; - if ( !current_state ) { return 0; } - state = *current_state; + acstate_t state = *current_state; + + const uint8_t* T = Tx; + const uint8_t* Tend = T + n; for (; T < Tend; T++ ) { - ps = NextState[state]; - - sindex = xlatcase[ T[0] ]; + acstate_t* ps = NextState[state]; + int sindex = xlatcase[ T[0] ]; /* test if this state has any matching patterns */ if ( ps[1] ) @@ -1892,8 +1870,9 @@ int acsm_search_dfa_banded( mlist = MatchList[state]; if (mlist) { - index = T - Tx; + int index = T - Tx; nfound++; + if (match (mlist->udata, mlist->rule_option_tree, index, context, mlist->neg_list) > 0) { @@ -1915,8 +1894,9 @@ int acsm_search_dfa_banded( mlist = MatchList[state]; if (mlist) { - index = T - Tx; + int index = T - Tx; nfound++; + if (match (mlist->udata, mlist->rule_option_tree, index, context, mlist->neg_list) > 0) { *current_state = state; @@ -1933,42 +1913,36 @@ int acsm_search_nfa( ACSM_STRUCT2* acsm, const uint8_t* Tx, int n, MpseMatch match, void* context, int* current_state) { - acstate_t state; - ACSM_PATTERN2* mlist; - const uint8_t* Tend; int nfound = 0; - const uint8_t* T; - int index; acstate_t** NextState= acsm->acsmNextState; acstate_t* FailState = acsm->acsmFailState; ACSM_PATTERN2** MatchList = acsm->acsmMatchList; - uint8_t Tchar; - - T = Tx; - Tend = T + n; if ( !current_state ) { return 0; } - state = *current_state; + acstate_t state = *current_state; + + const uint8_t* T = Tx; + const uint8_t* Tend = T + n; for (; T < Tend; T++ ) { + uint8_t Tchar = xlatcase[ *T ]; acstate_t nstate; - Tchar = xlatcase[ *T ]; - while ( (nstate=get_next_state_nfa(NextState[state],state,Tchar))==ACSM_FAIL_STATE2 ) state = FailState[state]; state = nstate; - mlist = MatchList[state]; + ACSM_PATTERN2* mlist = MatchList[state]; + if (mlist) { - index = T - Tx + 1; + int index = T - Tx + 1; nfound++; if (match (mlist->udata, mlist->rule_option_tree, index, context, mlist->neg_list) > 0) { @@ -2226,79 +2200,75 @@ int acsmPrintSummaryInfo2() #ifdef ACSMX2S_MAIN // Write a state table to disk -static void Write_DFA(ACSM_STRUCT2 * acsm, char * f) +static void Write_DFA(ACSM_STRUCT2* acsm, char* f) { - int k,i; - acstate_t * p, n, fmt, index, nb, bmatch; - acstate_t ** NextState = acsm->acsmNextState; - FILE * fp; + acstate_t** NextState = acsm->acsmNextState; + printf("Dump DFA - %d active states\n",acsm->acsmNumStates); - printf("Dump DFA - %d active states\n",acsm->acsmNumStates); + FILE* fp = fopen(f,"wb"); - fp = fopen(f,"wb"); - if(!fp) - { - printf("WARNING: could not write dfa to file - %s.\n",f); - return; - } + if (!fp) + { + printf("WARNING: could not write dfa to file - %s.\n",f); + return; + } - fwrite( &acsm->acsmNumStates, 4, 1, fp); + fwrite( &acsm->acsmNumStates, 4, 1, fp); - for(k=0;kacsmNumStates;k++) - { - p = NextState[k]; + for (int k=0; kacsmNumStates; k++) + { + acstate_t* p = NextState[k]; - if ( !p ) - continue; + if ( !p ) + continue; - fmt = *p++; + acstate_t fmt = *p++; + acstate_t bmatch = *p++; - bmatch = *p++; + fwrite(&fmt, sizeof(acstate_t), 1, fp); + fwrite(&bmatch, sizeof(acstate_t), 1, fp); - fwrite( &fmt, sizeof(acstate_t), 1, fp); - fwrite( &bmatch, sizeof(acstate_t), 1, fp); + if ( fmt == ACF_SPARSE ) + { + acstate_t n = *p++; + fwrite(&n, sizeof(acstate_t), 1, fp); + fwrite(p, n*2*sizeof(acstate_t), 1, fp); + } + else if ( fmt ==ACF_BANDED ) + { + acstate_t n = *p++; + fwrite(&n, sizeof(acstate_t), 1, fp); - if( fmt ==ACF_SPARSE ) - { - n = *p++; - fwrite( &n, sizeof(acstate_t), 1, fp); - fwrite( p, n*2*sizeof(acstate_t), 1, fp); - } - else if ( fmt ==ACF_BANDED ) - { - n = *p++; - fwrite( &n, sizeof(acstate_t), 1, fp); + acstate_t index = *p++; + fwrite(&index, sizeof(acstate_t), 1, fp); - index = *p++; - fwrite( &index, sizeof(acstate_t), 1, fp); + fwrite(p, sizeof(acstate_t), n, fp); + } + else if ( fmt ==ACF_SPARSE_BANDS ) + { + acstate_t nb = *p++; + fwrite(&nb, sizeof(acstate_t), 1, fp); - fwrite( p, sizeof(acstate_t), n, fp); - } - else if ( fmt ==ACF_SPARSE_BANDS ) - { - nb = *p++; - fwrite( &nb, sizeof(acstate_t), 1, fp); + for (int i=0; iacsmAlphabetSize, fp); + } - fwrite( p, sizeof(acstate_t), 1, fp); - } + //Print_DFA_MatchList( acsm, k); } - else if ( fmt == ACF_FULL ) - { - fwrite( p, sizeof(acstate_t), acsm->acsmAlphabetSize, fp); - } - - //Print_DFA_MatchList( acsm, k); - } - fclose(fp); + fclose(fp); } static int acsmSearch2( diff --git a/src/search_engines/bnfa_search.cc b/src/search_engines/bnfa_search.cc index f22c1045b..24527f8fc 100644 --- a/src/search_engines/bnfa_search.cc +++ b/src/search_engines/bnfa_search.cc @@ -622,13 +622,10 @@ static int _bnfa_conv_node_to_full(bnfa_trans_node_t* t, bnfa_state_t* full) #ifdef XXXX static int KcontainsJx(bnfa_trans_node_t* tk, bnfa_trans_node_t* tj) { - bnfa_trans_node_t* t; - int found; - while ( tj ) { - found=0; - for ( t=tk; t; t=t->next ) + int found=0; + for ( bnfa_trans_node_t* t=tk; t; t=t->next ) { if ( tj->key == t->key ) { @@ -673,12 +670,13 @@ static int _bnfa_opt_nfa(bnfa_struct_t* bnfa) #if 0 int cnt=0; #endif - int k, fs, fr; bnfa_state_t* FailState = bnfa->bnfaFailState; - for (k=2; kbnfaNumStates; k++) + for (int k=2; kbnfaNumStates; k++) { - fr = fs = FailState[k]; + int fs = FailState[k]; + int fr = fs; + while ( fs && KcontainsJ(bnfa->bnfaTransTable[k],bnfa->bnfaTransTable[fs]) ) { fs = FailState[fs]; @@ -1138,22 +1136,17 @@ void bnfaPrint(bnfa_struct_t* bnfa) #ifdef ALLOW_NFA_FULL else if ( bnfa->bnfaFormat == BNFA_FULL ) { - int i; - bnfa_state_t state; - bnfa_state_t* p; - bnfa_state_t** NextState; + bnfa_state_t** NextState = (bnfa_state_t**)bnfa->bnfaNextState; - NextState = (bnfa_state_t**)bnfa->bnfaNextState; if ( !NextState ) continue; - p = NextState[k]; - + bnfa_state_t* p = NextState[k]; printf("fs=%-4d nc=256 ",bnfa->bnfaFailState[k]); - for ( i=0; ibnfaAlphabetSize; i++ ) + for ( int i=0; ibnfaAlphabetSize; i++ ) { - state = p[i]; + bnfa_state_t state = p[i]; if ( state != 0 && state != BNFA_FAIL_STATE ) { @@ -1227,18 +1220,18 @@ void bnfaSetCase(bnfa_struct_t* p, int flag) void bnfaFree(bnfa_struct_t* bnfa) { int i; - bnfa_pattern_t* patrn, * ipatrn; - bnfa_match_node_t* mlist, * ilist; + bnfa_pattern_t* patrn; for (i = 0; i < bnfa->bnfaNumStates; i++) { /* free match list entries */ - mlist = bnfa->bnfaMatchList[i]; + bnfa_match_node_t* mlist = bnfa->bnfaMatchList[i]; while (mlist) { - ilist = mlist; + bnfa_match_node_t* ilist = mlist; mlist = mlist->next; + if (ilist->rule_option_tree && bnfa->agent) { bnfa->agent->tree_free(&(ilist->rule_option_tree)); @@ -1270,7 +1263,7 @@ void bnfaFree(bnfa_struct_t* bnfa) patrn = bnfa->bnfaPatterns; while (patrn) { - ipatrn=patrn; + bnfa_pattern_t* ipatrn=patrn; patrn=patrn->next; BNFA_FREE(ipatrn->casepatrn,ipatrn->n,bnfa->pat_memory); if (bnfa->agent && ipatrn->userdata) @@ -1479,31 +1472,25 @@ static inline unsigned _bnfa_search_full_nfa( bnfa_struct_t* bnfa, uint8_t* Tx, int n, MpseMatch match, void* context, bnfa_state_t state, int* current_state) { - uint8_t* Tend; - uint8_t* T; - uint8_t Tchar; - unsigned index; bnfa_state_t** NextState= bnfa->bnfaNextState; bnfa_state_t* FailState= bnfa->bnfaFailState; bnfa_match_node_t** MatchList= bnfa->bnfaMatchList; - bnfa_state_t* pcs; - bnfa_match_node_t* mlist; - bnfa_pattern_t* patrn; + unsigned nfound = 0; - int res; unsigned last_match=LAST_STATE_INIT; unsigned last_match_saved=LAST_STATE_INIT; - T = Tx; - Tend = T + n; + uint8_t* T = Tx; + uint8_t* Tend = T + n; for (; T < Tend; T++ ) { - Tchar = xlatcase[ *T ]; + uint8_t Tchar = xlatcase[ *T ]; for (;; ) { - pcs = NextState[state]; + bnfa_state_t* pcs = NextState[state]; + if ( pcs[Tchar] == 0 && state > 0 ) { state = FailState[state]; @@ -1524,19 +1511,19 @@ static inline unsigned _bnfa_search_full_nfa( last_match = state; { - mlist = MatchList[state]; + bnfa_match_node_t* mlist = MatchList[state]; + if (!mlist) - { continue; - } - patrn = (bnfa_pattern_t*)mlist->data; - index = T - Tx + 1; + + bnfa_pattern_t* patrn = (bnfa_pattern_t*)mlist->data; + unsigned index = T - Tx + 1; nfound++; /* Don't do anything specific for case sensitive patterns and not, * since that will be covered by the rule tree itself. Each tree * might have both case sensitive & case insensitive patterns. */ - res = match(patrn->userdata, mlist->rule_option_tree, index, context, + int res = match(patrn->userdata, mlist->rule_option_tree, index, context, mlist->neg_list); if ( res > 0 ) { @@ -1561,31 +1548,24 @@ static inline unsigned _bnfa_search_full_nfa_case( bnfa_struct_t* bnfa, uint8_t* Tx, int n, MpseMatch match, void* context, bnfa_state_t state, int* current_state) { - uint8_t* Tend; - uint8_t* T; - uint8_t Tchar; - unsigned index; bnfa_state_t** NextState= bnfa->bnfaNextState; bnfa_state_t* FailState= bnfa->bnfaFailState; bnfa_match_node_t** MatchList= bnfa->bnfaMatchList; - bnfa_state_t* pcs; - bnfa_match_node_t* mlist; - bnfa_pattern_t* patrn; + unsigned nfound = 0; unsigned last_match=LAST_STATE_INIT; unsigned last_match_saved=LAST_STATE_INIT; - int res; - T = Tx; - Tend = T + n; + uint8_t* T = Tx; + uint8_t* Tend = T + n; for (; T < Tend; T++ ) { - Tchar = *T; + uint8_t Tchar = *T; for (;; ) { - pcs = NextState[state]; + bnfa_state_t* pcs = NextState[state]; if ( pcs[Tchar] == 0 && state > 0 ) { state = FailState[state]; @@ -1606,19 +1586,19 @@ static inline unsigned _bnfa_search_full_nfa_case( last_match = state; { - mlist = MatchList[state]; + bnfa_match_node_t* mlist = MatchList[state]; + if (!mlist) - { continue; - } - patrn = (bnfa_pattern_t*)mlist->data; - index = T - Tx + 1; + + bnfa_pattern_t* patrn = (bnfa_pattern_t*)mlist->data; + unsigned index = T - Tx + 1; nfound++; /* Don't do anything specific for case (in)sensitive patterns * since that will be covered by the rule tree itself. Each * tree might have both case sensitive & case insensitive patterns. */ - res = match(patrn->userdata, mlist->rule_option_tree, index, context, + int res = match(patrn->userdata, mlist->rule_option_tree, index, context, mlist->neg_list); if ( res > 0 ) { @@ -1643,31 +1623,25 @@ static inline unsigned _bnfa_search_full_nfa_nocase( bnfa_struct_t* bnfa, uint8_t* Tx, int n, MpseMatch match, void* context, bnfa_state_t state, int* current_state) { - uint8_t* Tend; - uint8_t* T; - uint8_t Tchar; - unsigned index; - bnfa_state_t** NextState= bnfa->bnfaNextState; - bnfa_state_t* FailState= bnfa->bnfaFailState; - bnfa_match_node_t** MatchList= bnfa->bnfaMatchList; - bnfa_state_t* pcs; - bnfa_match_node_t* mlist; - bnfa_pattern_t* patrn; + bnfa_state_t** NextState = bnfa->bnfaNextState; + bnfa_state_t* FailState = bnfa->bnfaFailState; + bnfa_match_node_t** MatchList = bnfa->bnfaMatchList; + unsigned nfound = 0; unsigned last_match=LAST_STATE_INIT; unsigned last_match_saved=LAST_STATE_INIT; - int res; - T = Tx; - Tend = T + n; + uint8_t* T = Tx; + uint8_t* Tend = T + n; for (; T < Tend; T++ ) { - Tchar = xlatcase[ *T ]; + uint8_t Tchar = xlatcase[ *T ]; for (;; ) { - pcs = NextState[state]; + bnfa_state_t* pcs = NextState[state]; + if ( pcs[Tchar] == 0 && state > 0 ) { state = FailState[state]; @@ -1688,18 +1662,19 @@ static inline unsigned _bnfa_search_full_nfa_nocase( last_match = state; { - mlist = MatchList[state]; + bnfa_match_node_t* mlist = MatchList[state]; + if (!mlist) - { continue; - } - patrn = (bnfa_pattern_t*)mlist->data; - index = T - Tx + 1; + + bnfa_pattern_t* patrn = (bnfa_pattern_t*)mlist->data; + unsigned index = T - Tx + 1; + /* Don't do anything specific for case sensitive patterns and not, * since that will be covered by the rule tree itself. Each tree * might have both case sensitive & case insensitive patterns. */ - res = match(patrn->userdata, mlist->rule_option_tree, index, context, + int res = match(patrn->userdata, mlist->rule_option_tree, index, context, mlist->neg_list); if ( res > 0 ) { @@ -1734,17 +1709,14 @@ static inline unsigned _bnfa_search_full_nfa_nocase( */ static inline int _bnfa_binearch(const bnfa_state_t* a, int a_len, int val) { - int m, l, r; - int c; - - l = 0; - r = a_len - 1; + int l = 0; + int r = a_len - 1; while ( r >= l ) { - m = ( r + l ) >> 1; + int m = ( r + l ) >> 1; - c = a[m] >> BNFA_SPARSE_VALUE_SHIFT; + int c = a[m] >> BNFA_SPARSE_VALUE_SHIFT; if ( val == c ) { @@ -1843,25 +1815,19 @@ unsigned _bnfa_search_csparse_nfa( bnfa_struct_t* bnfa, const uint8_t* Tx, int n, MpseMatch match, void* context, unsigned sindex, int* current_state) { - bnfa_match_node_t* mlist; - const uint8_t* Tend; - const uint8_t* T; - uint8_t Tchar; - unsigned index; bnfa_match_node_t** MatchList = bnfa->bnfaMatchList; - bnfa_pattern_t* patrn; bnfa_state_t* transList = bnfa->bnfaTransList; + unsigned nfound = 0; unsigned last_match=LAST_STATE_INIT; unsigned last_match_saved=LAST_STATE_INIT; - int res; - T = Tx; - Tend = T + n; + const uint8_t* T = Tx; + const uint8_t* Tend = T + n; for (; Tdata; - index = T - Tx + 1; + bnfa_pattern_t* patrn = (bnfa_pattern_t*)mlist->data; + unsigned index = T - Tx + 1; nfound++; /* Don't do anything specific for case sensitive patterns and not, * since that will be covered by the rule tree itself. Each tree * might have both case sensitive & case insensitive patterns. */ - res = match(patrn->userdata, mlist->rule_option_tree, index, + int res = match(patrn->userdata, mlist->rule_option_tree, index, context, mlist->neg_list); if ( res > 0 ) { @@ -1980,25 +1947,19 @@ static inline unsigned _bnfa_search_csparse_nfa_nocase( bnfa_struct_t* bnfa, uint8_t* Tx, int n, MpseMatch match, void* context, unsigned sindex, int* current_state) { - bnfa_match_node_t* mlist; - uint8_t* Tend; - uint8_t* T; - uint8_t Tchar; - unsigned index; bnfa_match_node_t** MatchList = bnfa->bnfaMatchList; - bnfa_pattern_t* patrn; bnfa_state_t* transList = bnfa->bnfaTransList; + unsigned nfound = 0; unsigned last_match=LAST_STATE_INIT; unsigned last_match_saved=LAST_STATE_INIT; - int res; - T = Tx; - Tend = T + n; + uint8_t* T = Tx; + uint8_t* Tend = T + n; for (; Tdata; - index = T - Tx + 1; + bnfa_match_node_t* mlist = MatchList[ transList[sindex] ]; + bnfa_pattern_t* patrn = (bnfa_pattern_t*)mlist->data; + unsigned index = T - Tx + 1; nfound++; /* Don't do anything specific for case sensitive patterns and not, * since that will be covered by the rule tree itself. Each tree * might have both case sensitive & case insensitive patterns. */ - res = match(patrn->userdata, mlist->rule_option_tree, index, + int res = match(patrn->userdata, mlist->rule_option_tree, index, context, mlist->neg_list); if ( res > 0 ) { diff --git a/src/service_inspectors/back_orifice/back_orifice.cc b/src/service_inspectors/back_orifice/back_orifice.cc index 693c227a3..93ee0cf11 100644 --- a/src/service_inspectors/back_orifice/back_orifice.cc +++ b/src/service_inspectors/back_orifice/back_orifice.cc @@ -232,22 +232,18 @@ static void PrecalcPrefix() { uint8_t cookie_cyphertext[BO_MAGIC_SIZE]; const char* cookie_plaintext = "*!*QWTY?"; - int key; - int cookie_index; - const char* cp_ptr; /* cookie plaintext indexing pointer */ - uint16_t cyphertext_referent; memset(lookup1, 0, sizeof(lookup1)); memset(lookup2, 0, sizeof(lookup2)); - for (key=0; key<65536; key++) + for (int key=0; key<65536; key++) { /* setup to generate cyphertext for this key */ holdrand = key; - cp_ptr = cookie_plaintext; + const char* cp_ptr = cookie_plaintext; /* convert the plaintext cookie to cyphertext for this key */ - for (cookie_index=0; cookie_indexflow; - TcpStreamSession* session; if ( flow->session != nullptr) { if ( (flow->get_session_flags() & (SSNFLAG_ABORT_CLIENT | SSNFLAG_ABORT_SERVER)) == 0 ) { - session = (TcpStreamSession*)flow->session; - DceHttpProxySplitter* c2s_splitter = (DceHttpProxySplitter*)(session->get_splitter(true)); - DceHttpProxySplitter* s2c_splitter = (DceHttpProxySplitter*)(session->get_splitter(false)); + TcpStreamSession* session = (TcpStreamSession*)flow->session; + + DceHttpProxySplitter* c2s_splitter = + (DceHttpProxySplitter*)(session->get_splitter(true)); + + DceHttpProxySplitter* s2c_splitter = + (DceHttpProxySplitter*)(session->get_splitter(false)); + if ( c2s_splitter->cutover_inspector() && s2c_splitter->cutover_inspector() ) { dce_http_proxy_stats.http_proxy_sessions++; diff --git a/src/service_inspectors/dce_rpc/dce_http_server.cc b/src/service_inspectors/dce_rpc/dce_http_server.cc index 8ab75770e..7b64e3990 100644 --- a/src/service_inspectors/dce_rpc/dce_http_server.cc +++ b/src/service_inspectors/dce_rpc/dce_http_server.cc @@ -50,14 +50,16 @@ public: void DceHttpServer::clear(Packet* p) { Flow* flow = p->flow; - TcpStreamSession* session; if ( flow->session != nullptr) { if ( (flow->get_session_flags() & SSNFLAG_ABORT_SERVER) == 0 ) { - session = (TcpStreamSession*)flow->session; - DceHttpServerSplitter* splitter = (DceHttpServerSplitter*)(session->get_splitter(false)); + TcpStreamSession* session = (TcpStreamSession*)flow->session; + + DceHttpServerSplitter* splitter = + (DceHttpServerSplitter*)(session->get_splitter(false)); + if ( splitter->cutover_inspector()) { dce_http_server_stats.http_server_sessions++; diff --git a/src/service_inspectors/dce_rpc/dce_smb_transaction.cc b/src/service_inspectors/dce_rpc/dce_smb_transaction.cc index 929e4d156..3c8c8f478 100644 --- a/src/service_inspectors/dce_rpc/dce_smb_transaction.cc +++ b/src/service_inspectors/dce_rpc/dce_smb_transaction.cc @@ -570,6 +570,8 @@ static DCE2_Ret DCE2_SmbUpdateTransRequest(DCE2_SmbSsnData* ssd, // Can at most do a DCE/RPC bind case TRANS_CALL_NMPIPE: dce_alert(GID_DCE2, DCE2_SMB_DEPR_COMMAND_USED, (dce2CommonStats*)&dce2_smb_stats); + // fallthrough + // Aren't looking at these or the three above case TRANS_QUERY_NMPIPE_STATE: case TRANS_QUERY_NMPIPE_INFO: diff --git a/src/service_inspectors/dce_rpc/dce_smb_utils.cc b/src/service_inspectors/dce_rpc/dce_smb_utils.cc index 884bdf8bf..b1e2f3fb7 100644 --- a/src/service_inspectors/dce_rpc/dce_smb_utils.cc +++ b/src/service_inspectors/dce_rpc/dce_smb_utils.cc @@ -512,8 +512,7 @@ DCE2_SmbFileTracker* DCE2_SmbFindFileTracker(DCE2_SmbSsnData* ssd, break; } - - // Fall through for Windows 2000 for first request to file + // fallthrough case DCE2_POLICY__WIN2003: case DCE2_POLICY__WINXP: diff --git a/src/service_inspectors/dns/dns.cc b/src/service_inspectors/dns/dns.cc index 7bac0e8a3..2608db8aa 100644 --- a/src/service_inspectors/dns/dns.cc +++ b/src/service_inspectors/dns/dns.cc @@ -346,16 +346,13 @@ static uint16_t ParseDNSName( static uint16_t ParseDNSQuestion( const unsigned char* data, uint16_t bytes_unused, DNSData* dnsSessionData) { - uint16_t bytes_used = 0; - uint16_t new_bytes_unused = 0; - if ( !bytes_unused ) return 0; if (dnsSessionData->curr_rec_state < DNS_RESP_STATE_Q_NAME_COMPLETE) { - new_bytes_unused = ParseDNSName(data, bytes_unused, dnsSessionData); - bytes_used = bytes_unused - new_bytes_unused; + uint16_t new_bytes_unused = ParseDNSName(data, bytes_unused, dnsSessionData); + uint16_t bytes_used = bytes_unused - new_bytes_unused; if (dnsSessionData->curr_txt.name_state == DNS_RESP_STATE_NAME_COMPLETE) { @@ -416,16 +413,13 @@ static uint16_t ParseDNSQuestion( static uint16_t ParseDNSAnswer( const unsigned char* data, uint16_t bytes_unused, DNSData* dnsSessionData) { - uint16_t bytes_used = 0; - uint16_t new_bytes_unused = 0; - if ( !bytes_unused ) return 0; if (dnsSessionData->curr_rec_state < DNS_RESP_STATE_RR_NAME_COMPLETE) { - new_bytes_unused = ParseDNSName(data, bytes_unused, dnsSessionData); - bytes_used = bytes_unused - new_bytes_unused; + uint16_t new_bytes_unused = ParseDNSName(data, bytes_unused, dnsSessionData); + uint16_t bytes_used = bytes_unused - new_bytes_unused; if (dnsSessionData->curr_txt.name_state == DNS_RESP_STATE_NAME_COMPLETE) { diff --git a/src/service_inspectors/ftp_telnet/ftp_print.cc b/src/service_inspectors/ftp_telnet/ftp_print.cc index b7cb9b3c5..a92228b1d 100644 --- a/src/service_inspectors/ftp_telnet/ftp_print.cc +++ b/src/service_inspectors/ftp_telnet/ftp_print.cc @@ -227,7 +227,6 @@ int PrintFTPClientConf(FTP_CLIENT_PROTO_CONF* ClientConf) int PrintFTPServerConf(FTP_SERVER_PROTO_CONF* ServerConf) { - char buf[BUF_SIZE+1]; int iRet; FTP_CMD_CONF* FTPCmd; @@ -253,10 +252,12 @@ int PrintFTPServerConf(FTP_SERVER_PROTO_CONF* ServerConf) FTPCmd = ftp_cmd_lookup_first(ServerConf->cmd_lookup, &iRet); while (FTPCmd != nullptr) { - memset(buf, 0, BUF_SIZE+1); + char buf[BUF_SIZE+1]; snprintf(buf, BUF_SIZE, " %s { %u ", FTPCmd->cmd_name, FTPCmd->max_param_len); + #ifdef PRINT_DEFAULT_CONFIGS + // FIXIT-L should append, not overwrite if (FTPCmd->data_chan_cmd) snprintf(buf, BUF_SIZE, "%s", "data_chan "); if (FTPCmd->data_xfer_cmd) diff --git a/src/service_inspectors/ftp_telnet/pp_ftp.cc b/src/service_inspectors/ftp_telnet/pp_ftp.cc index d1d4cfd24..8bd19cf4d 100644 --- a/src/service_inspectors/ftp_telnet/pp_ftp.cc +++ b/src/service_inspectors/ftp_telnet/pp_ftp.cc @@ -1294,17 +1294,16 @@ static int do_stateful_checks(FTP_SESSION* session, Packet* p, #define FTP_RESPONSE_2BCONT 2 #define FTP_RESPONSE_CONT 3 #define FTP_RESPONSE_ENDCONT 4 + int check_ftp(FTP_SESSION* ftpssn, Packet* p, int iMode) { int iRet = FTPP_SUCCESS; int encrypted = 0; int space = 0; - long state = FTP_CMD_OK; int rsp_code = 0; FTP_CLIENT_REQ* req; FTP_CMD_CONF* CmdConf = nullptr; - const unsigned char* read_ptr; const unsigned char* end = p->data + p->dsize; if ( DecodeBuffer.len ) @@ -1325,11 +1324,10 @@ int check_ftp(FTP_SESSION* ftpssn, Packet* p, int iMode) while (req->pipeline_req) { - state = FTP_CMD_OK; + long state = FTP_CMD_OK; - /* Starts at the beginning of the buffer/line, - * so next up is a command */ - read_ptr = (const unsigned char*)req->pipeline_req; + /* Starts at the beginning of the buffer/line, so next up is a command */ + const unsigned char* read_ptr = (const unsigned char*)req->pipeline_req; /* but first we ignore leading white space */ while ( (read_ptr < end) && diff --git a/src/service_inspectors/ftp_telnet/pp_telnet.cc b/src/service_inspectors/ftp_telnet/pp_telnet.cc index 372bf0199..76fda0e20 100644 --- a/src/service_inspectors/ftp_telnet/pp_telnet.cc +++ b/src/service_inspectors/ftp_telnet/pp_telnet.cc @@ -96,7 +96,6 @@ int normalize_telnet( { int ret = FTPP_NORMALIZED; const unsigned char* read_ptr, * sb_start = nullptr; - int saw_ayt = 0; unsigned char* write_ptr; const unsigned char* end; int normalization_required = 0; @@ -193,12 +192,13 @@ int normalize_telnet( while ((read_ptr < end) && (write_ptr < ((unsigned char*)buf.data) + sizeof(buf.data))) { - saw_ayt = 0; /* if the following byte isn't a subnegotiation initialization */ if (((read_ptr + 1) < end) && (*read_ptr == (unsigned char)TNC_IAC) && (*(read_ptr + 1) != (unsigned char)TNC_SB)) { + int saw_ayt = 0; + /* NOPs are two bytes long */ switch (*((const unsigned char*)(read_ptr + 1))) { diff --git a/src/service_inspectors/gtp/gtp_parser.cc b/src/service_inspectors/gtp/gtp_parser.cc index 32e8e499a..4ea1b0699 100644 --- a/src/service_inspectors/gtp/gtp_parser.cc +++ b/src/service_inspectors/gtp/gtp_parser.cc @@ -83,14 +83,13 @@ struct GTP_IE_Hdr static void convertToHex(char* output, int outputSize, const uint8_t* input, int inputSize) { int i = 0; - int length; int numBytesInLine = 0; int totalBytes = outputSize; char* buf_ptr = output; while ((i < inputSize)&&(totalBytes > 0)) { - length = safe_snprintf(buf_ptr, totalBytes, "%.2x ", (uint8_t)input[i]); + int length = safe_snprintf(buf_ptr, totalBytes, "%.2x ", (uint8_t)input[i]); buf_ptr += length; totalBytes -= length; if (totalBytes < 0) @@ -110,13 +109,11 @@ static void convertToHex(char* output, int outputSize, const uint8_t* input, int /* Display the information elements*/ static void printInfoElements(GTP_IEData* info_elements, GTPMsg* msg) { - int i; - - for (i=0; i < MAX_GTP_IE_CODE + 1; i++) + for (int i=0; i < MAX_GTP_IE_CODE + 1; i++) { - char buf[STD_BUF]; if (info_elements[i].msg_id == msg->msg_id) { + char buf[STD_BUF]; convertToHex( (char*)buf, sizeof(buf), msg->gtp_header + info_elements[i].shift, info_elements[i].length); DEBUG_WRAP(DebugFormat(DEBUG_GTP, "Info type: %.3d, content: %s\n", i, buf); ); @@ -128,22 +125,17 @@ static void printInfoElements(GTP_IEData* info_elements, GTPMsg* msg) static int gtp_processInfoElements( const GTPConfig& config, GTPMsg* msg, const uint8_t* buff, uint16_t len) { - const uint8_t* start; - uint8_t type; - int32_t unprocessed_len; - uint8_t previous_type; + const uint8_t* start = buff; + uint8_t previous_type = (uint8_t)*start; + int32_t unprocessed_len = len; DEBUG_WRAP(DebugFormat(DEBUG_GTP, "Information elements: length: %d\n", len); ); - start = buff; - previous_type = (uint8_t)*start; - unprocessed_len = len; - while ( unprocessed_len > 0) { - type = *start; + uint8_t type = *start; - if (previous_type > type) + if (previous_type > type) alert(GTP_EVENT_OUT_OF_ORDER_IE); const GTP_InfoElement* ie = &config.infov[msg->version][type]; @@ -293,7 +285,6 @@ static int gtp_parse_v0(GTPMsg* msg, const uint8_t* buff, uint16_t gtp_len) ********************************************************************/ static int gtp_parse_v1(GTPMsg* msg, const uint8_t* buff, uint16_t gtp_len) { - uint8_t next_hdr_type; const GTP_C_Hdr* hdr; DEBUG_WRAP(DebugMessage(DEBUG_GTP, "This ia a GTP v1 packet.\n"); ); @@ -311,7 +302,7 @@ static int gtp_parse_v1(GTPMsg* msg, const uint8_t* buff, uint16_t gtp_len) return false; } - next_hdr_type = *(buff + msg->header_len - 1); + uint8_t next_hdr_type = *(buff + msg->header_len - 1); /*Check extension headers*/ while (next_hdr_type) diff --git a/src/service_inspectors/sip/ips_sip_stat_code.cc b/src/service_inspectors/sip/ips_sip_stat_code.cc index aa934e104..34a0219e0 100644 --- a/src/service_inspectors/sip/ips_sip_stat_code.cc +++ b/src/service_inspectors/sip/ips_sip_stat_code.cc @@ -160,12 +160,12 @@ bool SipStatCodeModule::begin(const char*, int, SnortConfig*) bool SipStatCodeModule::set(const char*, Value& v, SnortConfig*) { - unsigned long statCode; if (num_tokens < SIP_NUM_STAT_CODE_MAX) { if ( v.is("*code") ) { - statCode = v.get_long(); + unsigned long statCode = v.get_long(); + if ((statCode > MAX_STAT_CODE) || ((statCode > NUM_OF_RESPONSE_TYPES - 1) && (statCode < MIN_STAT_CODE))) { diff --git a/src/service_inspectors/sip/sip_parser.cc b/src/service_inspectors/sip/sip_parser.cc index 438781d5d..21dfdb46f 100644 --- a/src/service_inspectors/sip/sip_parser.cc +++ b/src/service_inspectors/sip/sip_parser.cc @@ -449,25 +449,23 @@ static bool sip_startline_parse(SIPMsg* msg, const char* buff, const char* end, * false * true ********************************************************************/ -static bool sip_headers_parse(SIPMsg* msg, const char* buff, const char* end, const char** headEnd, +static bool sip_headers_parse( + SIPMsg* msg, const char* buff, const char* end, const char** headEnd, SIP_PROTO_CONF* config) { const char* next; - const char* start; - int length; - int numOfLineBreaks; + const char* start = buff; int lastFieldIndex = SIP_PARSE_NOFOLDING; - start = buff; /* * The end of header is defined by two CRLFs, or CRCR, or LFLF */ - numOfLineBreaks = sip_find_linebreak(start, end, &next); + int numOfLineBreaks = sip_find_linebreak(start, end, &next); while (numOfLineBreaks > 0) { /*Processing this line*/ - length = next - start - numOfLineBreaks; + int length = next - start - numOfLineBreaks; DebugFormat(DEBUG_SIP, "Header line: %.*s\n", length, start); /*Process headers*/ @@ -508,15 +506,12 @@ static bool sip_headers_parse(SIPMsg* msg, const char* buff, const char* end, co ********************************************************************/ static bool sip_body_parse(SIPMsg* msg, const char* buff, const char* end, const char** bodyEnd) { - int length; - const char* next; - const char* start; - int numOfLineBreaks; - #ifdef DEBUG_MSGS - length = end - buff; - DebugFormat(DEBUG_SIP, "Body length: %d\n", length); - DebugFormat(DEBUG_SIP, "Body line: %.*s\n", length, buff); + { + int length = end - buff; + DebugFormat(DEBUG_SIP, "Body length: %d\n", length); + DebugFormat(DEBUG_SIP, "Body line: %.*s\n", length, buff); + } #endif // Initialize it @@ -530,17 +525,18 @@ static bool sip_body_parse(SIPMsg* msg, const char* buff, const char* end, const // Create a media session msg->mediaSession = (SIP_MediaSession*)snort_calloc(sizeof(SIP_MediaSession)); - start = buff; + const char* start = buff; /* * The end of body is defined by two CRLFs or CRCR or LFLF */ - numOfLineBreaks = sip_find_linebreak(start, end, &next); + const char* next; + int numOfLineBreaks = sip_find_linebreak(start, end, &next); while (numOfLineBreaks > 0) { /*Processing this line*/ - length = next - start - numOfLineBreaks; + int length = next - start - numOfLineBreaks; DebugFormat(DEBUG_SIP, "Body line: %.*s\n", length, start); /*Process body fields*/ diff --git a/src/service_inspectors/sip/sip_utils.cc b/src/service_inspectors/sip/sip_utils.cc index b1e429b53..174cc90a5 100644 --- a/src/service_inspectors/sip/sip_utils.cc +++ b/src/service_inspectors/sip/sip_utils.cc @@ -119,17 +119,18 @@ SIPMethodNode* SIP_FindMethod(SIPMethodlist methods, const char* methodName, uns ********************************************************************/ uint32_t strToHash(const char* str, int length) { - uint32_t a,b,c,tmp; - int i,j,k,l; - a = b = c = 0; + uint32_t a = 0, b = 0, c = 0; + int i,j; + for (i=0,j=0; i 4) k=4; - for (l=0; lnormalize == NORMALIZE_ALL) sfsnprintfappend(buf, sizeof(buf) - 1, "all"); + else if(config->normalize == NORMALIZE_NONE) sfsnprintfappend(buf, sizeof(buf) - 1, "none"); + else if(config->normalize == NORMALIZE_CMDS) { - for (cmd = config->cmds; cmd->name != nullptr; cmd++) + for (SMTPToken* cmd = config->cmds; cmd->name != nullptr; cmd++) { if (config->cmd_config[cmd->search_id].normalize) { @@ -409,10 +405,11 @@ static void SMTP_PrintConfig(SMTP_PROTO_CONF *config) { snprintf(buf, sizeof(buf) - 1, " Max Specific Command Line Length: "); + int max_line_len_count = 0; - for (cmd = config->cmds; cmd->name != nullptr; cmd++) + for (SMTPToken* cmd = config->cmds; cmd->name != nullptr; cmd++) { - max_line_len = config->cmd_config[cmd->search_id].max_line_len; + int max_line_len = config->cmd_config[cmd->search_id].max_line_len; if (max_line_len != 0) { @@ -465,7 +462,7 @@ static void SMTP_PrintConfig(SMTP_PROTO_CONF *config) snprintf(buf, sizeof(buf) - 1, " Alert on commands: "); - for (cmd = config->cmds; cmd->name != nullptr; cmd++) + for (SMTPToken* cmd = config->cmds; cmd->name != nullptr; cmd++) { if (config->cmd_config[cmd->search_id].alert) { @@ -1060,23 +1057,13 @@ static void SMTP_ProcessClientPacket(SMTP_PROTO_CONF* config, Packet* p, SMTPDat * * @return None */ -static void SMTP_ProcessServerPacket(SMTP_PROTO_CONF* config, Packet* p, SMTPData* smtp_ssn, - int* next_state) +static void SMTP_ProcessServerPacket( + SMTP_PROTO_CONF* config, Packet* p, SMTPData* smtp_ssn, int* next_state) { - int resp_found; - const uint8_t* ptr; - const uint8_t* end; - const uint8_t* eolm; - const uint8_t* eol; - int resp_line_len; -#ifdef DEBUG_MSGS - const uint8_t* dash; -#endif - *next_state = 0; - ptr = p->data; - end = p->data + p->dsize; + const uint8_t* ptr = p->data; + const uint8_t* end = p->data + p->dsize; if (smtp_ssn->state == STATE_TLS_SERVER_PEND) { @@ -1105,13 +1092,17 @@ static void SMTP_ProcessServerPacket(SMTP_PROTO_CONF* config, Packet* p, SMTPDat while (ptr < end) { + const uint8_t* eol; + const uint8_t* eolm; + SMTP_GetEOL(ptr, end, &eol, &eolm); - resp_line_len = eol - ptr; + int resp_line_len = eol - ptr; /* Check for response code */ smtp_current_search = &smtp_resp_search[0]; - resp_found = smtp_resp_search_mpse->find( + + int resp_found = smtp_resp_search_mpse->find( (const char*)ptr, resp_line_len, SMTP_SearchStrFound); if (resp_found > 0) @@ -1144,7 +1135,7 @@ static void SMTP_ProcessServerPacket(SMTP_PROTO_CONF* config, Packet* p, SMTPDat } #ifdef DEBUG_MSGS - dash = ptr + smtp_search_info.index + smtp_search_info.length; + const uint8_t* dash = ptr + smtp_search_info.index + smtp_search_info.length; /* only add response if not a dash after response code */ if ((dash == eolm) || ((dash < eolm) && (*dash != '-'))) @@ -1378,14 +1369,11 @@ static void SMTP_RegXtraDataFuncs(SMTP_PROTO_CONF* config) config->xtra_ehdrs_id = Stream::reg_xtra_data_cb(SMTP_GetEmailHdrs); } -int SmtpMime::handle_header_line(const uint8_t* ptr, const uint8_t* eol, - int max_header_len) +int SmtpMime::handle_header_line( + const uint8_t* ptr, const uint8_t* eol, int max_header_len) { - int ret; - int header_line_len; - MimeSession* mime_ssn = (MimeSession*)this; /* get length of header line */ - header_line_len = eol - ptr; + int header_line_len = eol - ptr; if (max_header_len) DetectionEngine::queue_event(GID_SMTP, SMTP_HEADER_NAME_OVERFLOW); @@ -1401,16 +1389,17 @@ int SmtpMime::handle_header_line(const uint8_t* ptr, const uint8_t* eol, * currently the code does not normalize headers */ if (smtp_normalizing) { - ret = SMTP_CopyToAltBuffer(nullptr, ptr, eol - ptr); + int ret = SMTP_CopyToAltBuffer(nullptr, ptr, eol - ptr); + if (ret == -1) return (-1); } if (config->log_config.log_email_hdrs) { - if (mime_ssn->get_data_state() == STATE_DATA_HEADER) + if (get_data_state() == STATE_DATA_HEADER) { - mime_ssn->get_log_state()->log_email_hdrs(ptr, eol - ptr); + get_log_state()->log_email_hdrs(ptr, eol - ptr); } } diff --git a/src/service_inspectors/smtp/smtp_xlink2state.cc b/src/service_inspectors/smtp/smtp_xlink2state.cc index 5051ed496..35fe4ae51 100644 --- a/src/service_inspectors/smtp/smtp_xlink2state.cc +++ b/src/service_inspectors/smtp/smtp_xlink2state.cc @@ -57,18 +57,16 @@ static char get_xlink_keyword(const uint8_t*, const uint8_t*); */ static uint32_t get_xlink_hex_value(const uint8_t* buf, const uint8_t* end) { - char c; uint32_t value = 0; - const uint8_t* hex_end; if ((end - buf) < 8) return 0; - hex_end = buf + 8; + const uint8_t* hex_end = buf + 8; while (buf < hex_end) { - c = toupper((int)*buf); + char c = toupper((int)*buf); /* Make sure it is a number or hex char; if not return with what we have */ if (isdigit((int)c)) diff --git a/src/service_inspectors/ssh/ssh.cc b/src/service_inspectors/ssh/ssh.cc index aee3ab4fd..554f53fab 100644 --- a/src/service_inspectors/ssh/ssh.cc +++ b/src/service_inspectors/ssh/ssh.cc @@ -572,10 +572,8 @@ static unsigned int ProcessSSHKeyInitExchange(SSHData* sessionp, Packet* p, static unsigned int ProcessSSHKeyExchange(SSHData* sessionp, Packet* p, uint8_t direction, unsigned int offset) { - const SSH2Packet* ssh2p = nullptr; uint16_t dsize = p->dsize; const unsigned char* data = p->data; - unsigned int ssh_length; bool next_packet = true; unsigned int npacket_offset = 0; @@ -590,8 +588,8 @@ static unsigned int ProcessSSHKeyExchange(SSHData* sessionp, Packet* p, while (next_packet) { - ssh2p = (const SSH2Packet*)(data + npacket_offset); - ssh_length = SSHPacket_GetLength(ssh2p, dsize); + const SSH2Packet* ssh2p = (const SSH2Packet*)(data + npacket_offset); + unsigned ssh_length = SSHPacket_GetLength(ssh2p, dsize); if (ssh_length == 0) { diff --git a/src/sfip/sf_ipvar.cc b/src/sfip/sf_ipvar.cc index 24d7bc527..75dda8adf 100644 --- a/src/sfip/sf_ipvar.cc +++ b/src/sfip/sf_ipvar.cc @@ -183,13 +183,12 @@ static inline void sfip_node_freelist(sfip_node_t* root) static inline sfip_node_t* _sfvar_deep_copy_list(const sfip_node_t* idx) { - sfip_node_t* ret, * temp, * prev; - - ret = temp = nullptr; + sfip_node_t* ret = nullptr; + sfip_node_t* temp = nullptr; for (; idx; idx = idx->next) { - prev = temp; + sfip_node_t* prev = temp; temp = (sfip_node_t*)snort_calloc(sizeof(*temp)); temp->ip = new SfCidr(); diff --git a/src/sfrt/sfrt.cc b/src/sfrt/sfrt.cc index 17e94e3d9..a6a22aae9 100644 --- a/src/sfrt/sfrt.cc +++ b/src/sfrt/sfrt.cc @@ -720,18 +720,16 @@ static inline int allocateTableIndex(table_t* table) int main() { - table_t* dir; uint32_t ip_list[NUM_IPS]; /* entirely arbitrary */ char data[NUM_DATA]; /* also entirely arbitrary */ - uint32_t index, val; - for (index=0; indexallocated = 0; table->dimensions = (int*)snort_alloc(sizeof(int)*count); table->dim_size = count; + va_list ap; va_start(ap, count); - for (index=0; index < count; index++) - { - val = va_arg(ap, int); - table->dimensions[index] = val; - } + for (int index=0; index < count; index++) + table->dimensions[index] = va_arg(ap, int); va_end(ap); @@ -367,7 +361,6 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, GENERIC ptr, dir_sub_table_t* sub_table, dir_table_t* root_table) { word index; - uint32_t fill; { uint32_t local_index, i; /* need to handle bits usage across multiple 32bit vals within IPv6. */ @@ -397,7 +390,7 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, GENERIC ptr, /* Calculate how many entries need to be filled * in this table. If the table is 24 bits wide, and the entry * is 20 bytes long, 2^4 entries need to be filled. */ - fill = 1 << (sub_table->width - cur_len); + uint32_t fill = 1 << (sub_table->width - cur_len); index = (index >> (sub_table->width - cur_len)) << (sub_table->width - cur_len); @@ -644,7 +637,6 @@ static int _dir_sub_remove(IPLOOKUP* ip, int length, int cur_len, dir_sub_table_t* sub_table, dir_table_t* root_table) { word index; - uint32_t fill; uint32_t valueIndex = 0; { @@ -676,7 +668,7 @@ static int _dir_sub_remove(IPLOOKUP* ip, int length, int cur_len, /* Calculate how many entries need to be removed (filled with 0) * in this table. If the table is 24 bits wide, and the entry * is 20 bytes long, 2^4 entries need to be filled. */ - fill = 1 << (sub_table->width - cur_len); + uint32_t fill = 1 << (sub_table->width - cur_len); index = (index >> (sub_table->width - cur_len)) << (sub_table->width - cur_len); diff --git a/src/sfrt/sfrt_flat_dir.cc b/src/sfrt/sfrt_flat_dir.cc index e129e0e09..a98490319 100644 --- a/src/sfrt/sfrt_flat_dir.cc +++ b/src/sfrt/sfrt_flat_dir.cc @@ -113,7 +113,6 @@ static TABLE_PTR _sub_table_flat_new(dir_table_flat_t* root, uint32_t dimension, TABLE_PTR sfrt_dir_flat_new(uint32_t mem_cap, int count,...) { va_list ap; - uint32_t val; int index; TABLE_PTR table_ptr; dir_table_flat_t* table; @@ -137,7 +136,7 @@ TABLE_PTR sfrt_dir_flat_new(uint32_t mem_cap, int count,...) for (index=0; index < count; index++) { - val = va_arg(ap, int); + uint32_t val = va_arg(ap, int); table->dimensions[index] = val; } @@ -363,7 +362,6 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, INFO ptr, INFO* data) { word index; - uint32_t fill; uint8_t* base = (uint8_t*)segment_basePtr(); dir_sub_table_flat_t* sub_table = (dir_sub_table_flat_t*)(&base[sub_ptr]); @@ -396,7 +394,7 @@ static int _dir_sub_insert(IPLOOKUP* ip, int length, int cur_len, INFO ptr, /* Calculate how many entries need to be filled * in this table. If the table is 24 bits wide, and the entry * is 20 bytes long, 2^4 entries need to be filled. */ - fill = 1 << (sub_table->width - cur_len); + uint32_t fill = 1 << (sub_table->width - cur_len); index = (index >> (sub_table->width - cur_len)) << (sub_table->width - cur_len); diff --git a/src/stream/libtcp/tcp_stream_tracker.cc b/src/stream/libtcp/tcp_stream_tracker.cc index d6601bd67..938274b46 100644 --- a/src/stream/libtcp/tcp_stream_tracker.cc +++ b/src/stream/libtcp/tcp_stream_tracker.cc @@ -142,8 +142,6 @@ bool TcpStreamTracker::compare_mac_addresses(const uint8_t eth_addr[]) void TcpStreamTracker::cache_mac_address(TcpSegmentDescriptor& tsd, uint8_t direction) { - int i; - /* Not Ethernet based, nothing to do */ if ( tsd.get_pkt()->is_eth() ) { @@ -153,19 +151,19 @@ void TcpStreamTracker::cache_mac_address(TcpSegmentDescriptor& tsd, uint8_t dire if ( direction == FROM_CLIENT ) { if ( client_tracker ) - for ( i = 0; i < 6; i++ ) + for ( int i = 0; i < 6; i++ ) mac_addr[i] = eh->ether_src[i]; else - for ( i = 0; i < 6; i++ ) + for ( int i = 0; i < 6; i++ ) mac_addr[i] = eh->ether_dst[i]; } else { if ( client_tracker ) - for ( i = 0; i < 6; i++ ) + for ( int i = 0; i < 6; i++ ) mac_addr[i] = eh->ether_dst[i]; else - for ( i = 0; i < 6; i++ ) + for ( int i = 0; i < 6; i++ ) mac_addr[i] = eh->ether_src[i]; } diff --git a/src/stream/paf.cc b/src/stream/paf.cc index 30100aca0..2eeb047be 100644 --- a/src/stream/paf.cc +++ b/src/stream/paf.cc @@ -326,14 +326,12 @@ int32_t paf_check ( { px.ft = FT_NOP; uint32_t idx = px.idx; - uint32_t shift; - int32_t fp; bool cont = paf_eval(ss, ps, px, ssn, *flags, data, len); if ( px.ft != FT_NOP ) { - fp = paf_flush(ps, px, flags); + int32_t fp = paf_flush(ps, px, flags); paf_jump(ps, fp); return fp; } @@ -342,7 +340,7 @@ int32_t paf_check ( if ( px.idx > idx ) { - shift = px.idx - idx; + uint32_t shift = px.idx - idx; if ( shift > len ) shift = len; data += shift; diff --git a/src/stream/stream.cc b/src/stream/stream.cc index 6bd52f91c..73854f5aa 100644 --- a/src/stream/stream.cc +++ b/src/stream/stream.cc @@ -431,10 +431,9 @@ int16_t Stream::get_application_protocol_id(Flow* flow) /* Not caching the source and dest host_entry in the session so we can * swap the table out after processing this packet if we need * to. */ - int16_t protocol = 0; if (!flow) - return protocol; + return 0; if ( flow->ssn_state.application_protocol == -1 ) return 0; diff --git a/src/stream/tcp/tcp_normalizer.cc b/src/stream/tcp/tcp_normalizer.cc index f257c19b1..cf7cd18c2 100644 --- a/src/stream/tcp/tcp_normalizer.cc +++ b/src/stream/tcp/tcp_normalizer.cc @@ -75,7 +75,7 @@ void TcpNormalizer::trim_payload( { uint16_t fat = tsd.get_seg_len() - max; tsd.set_seg_len(max); - tsd.get_pkt()->packet_flags |= (PKT_MODIFIED | PKT_RESIZED); + tsd.get_pkt()->packet_flags |= PKT_RESIZED; tsd.set_end_seq(tsd.get_end_seq() - fat); } diff --git a/src/stream/tcp/tcp_segment_node.h b/src/stream/tcp/tcp_segment_node.h index e6be61ded..34c0afe29 100644 --- a/src/stream/tcp/tcp_segment_node.h +++ b/src/stream/tcp/tcp_segment_node.h @@ -89,14 +89,13 @@ public: uint32_t clear() { - TcpSegmentNode* dump_me; int i = 0; DebugMessage(DEBUG_STREAM_STATE, "Clearing segment list.\n"); while ( head ) { i++; - dump_me = head; + TcpSegmentNode* dump_me = head; head = head->next; dump_me->term( ); } diff --git a/src/stream/tcp/tcp_session.cc b/src/stream/tcp/tcp_session.cc index 00d1f6404..647bdb111 100644 --- a/src/stream/tcp/tcp_session.cc +++ b/src/stream/tcp/tcp_session.cc @@ -689,8 +689,6 @@ void TcpSession::check_for_session_hijack(TcpSegmentDescriptor& tsd) { if (!(tsd.get_pkt()->pkth->flags & DAQ_PKT_FLAG_PRE_ROUTING)) { - uint32_t event_code = 0; - if ( tsd.get_pkt()->is_eth() ) { // if flag is set, guaranteed to have an eth layer @@ -705,6 +703,8 @@ void TcpSession::check_for_session_hijack(TcpSegmentDescriptor& tsd) listener->compare_mac_addresses(eh->ether_src) ) ) return; + uint32_t event_code = 0; + if ( t_hijack ) { if ( p->is_from_client() ) diff --git a/src/target_based/sftarget_reader.cc b/src/target_based/sftarget_reader.cc index 0d033a4d1..f9a41df52 100644 --- a/src/target_based/sftarget_reader.cc +++ b/src/target_based/sftarget_reader.cc @@ -350,7 +350,6 @@ void SFAT_UpdateApplicationProtocol(SfIp* ipAddr, uint16_t port, uint16_t protoc HostAttributeEntry* host_entry; ApplicationEntry* service; unsigned service_count = 0; - int rval; host_entry = (HostAttributeEntry*)sfrt_lookup(ipAddr, curr_cfg->lookupTable); @@ -362,8 +361,10 @@ void SFAT_UpdateApplicationProtocol(SfIp* ipAddr, uint16_t port, uint16_t protoc host_entry = (HostAttributeEntry*)snort_calloc(sizeof(*host_entry)); host_entry->ipAddr.set(*ipAddr); - if ((rval = sfrt_insert(&host_entry->ipAddr, (unsigned char)host_entry->ipAddr.get_bits(), host_entry, - RT_FAVOR_SPECIFIC, curr_cfg->lookupTable)) != RT_SUCCESS) + int rval = sfrt_insert(&host_entry->ipAddr, (unsigned char)host_entry->ipAddr.get_bits(), + host_entry, RT_FAVOR_SPECIFIC, curr_cfg->lookupTable); + + if ( rval != RT_SUCCESS) { FreeHostEntry(host_entry); return; diff --git a/src/utils/kmap.cc b/src/utils/kmap.cc index afe25c192..786dde38c 100644 --- a/src/utils/kmap.cc +++ b/src/utils/kmap.cc @@ -55,9 +55,7 @@ void KMapSetNoCase(KMAP* km, int flag) */ static int KMapFreeNodeList(KMAP* km) { - KEYNODE* k, * kold; - - for ( k=km->keylist; k; ) + for ( KEYNODE* k=km->keylist; k; ) { if ( k->key ) { @@ -67,7 +65,7 @@ static int KMapFreeNodeList(KMAP* km) { km->userfree(k->userdata); } - kold = k; + KEYNODE* kold = k; k = k->next; snort_free(kold); } @@ -98,23 +96,18 @@ static void KMapFreeNode(KMAP* km, KMAPNODE* r) */ void KMapDelete(KMAP* km) { - KMAPNODE* r; - int i; - - /* Free the tree - on root node at a time */ - for (i=0; i<256; i++) + /* Free the tree - one root node at a time */ + for (int i=0; i<256; i++) { - r = km->root[i]; + KMAPNODE* r = km->root[i]; + if ( r ) - { KMapFreeNode(km,r); - } + km->root[i] = nullptr; } - /* Free the node list */ KMapFreeNodeList(km); - snort_free(km); } @@ -172,10 +165,8 @@ static KMAPNODE* KMapCreateNode(KMAP* km) */ int KMapAdd(KMAP* km, void* key, int n, void* userdata) { - int i,ksize; int type = 0; const unsigned char* P = (unsigned char*)key; - KMAPNODE* root; std::string xkey; if ( n <= 0 ) @@ -191,14 +182,15 @@ int KMapAdd(KMAP* km, void* key, int n, void* userdata) { xkey.resize(n); - for (i=0; inocase ) { xkey.resize(n); - for (i=0; iroot[ *T ]; + KMAPNODE* root = ks->root[ *T ]; if ( !root ) return nullptr; diff --git a/src/utils/sflsq.cc b/src/utils/sflsq.cc index 0f7522b3b..fe49c6253 100644 --- a/src/utils/sflsq.cc +++ b/src/utils/sflsq.cc @@ -317,14 +317,12 @@ int sflist_count(SF_LIST* s) */ void sflist_free_all(SF_LIST* s, void (* nfree)(void*) ) { - void* p; - if (!s) return; while ( s->count > 0 ) { - p = sflist_remove_head (s); + void* p = sflist_remove_head (s); if ( p && nfree ) nfree(p); @@ -339,14 +337,12 @@ void sfqueue_free_all(SF_QUEUE* s,void (* nfree)(void*) ) void sflist_static_free_all(SF_LIST* s, void (* nfree)(void*) ) { - void* p; - if (!s) return; while ( s->count > 0 ) { - p = sflist_remove_head (s); + void* p = sflist_remove_head (s); if ( p && nfree ) nfree(p); diff --git a/src/utils/util.cc b/src/utils/util.cc index fad7d84a0..7ac5d239c 100644 --- a/src/utils/util.cc +++ b/src/utils/util.cc @@ -255,7 +255,6 @@ void CreatePidFile(pid_t pid) { pid_lockfilename = snort_conf->pid_filename; pid_lockfilename += ".lck"; - int lock_fd; /* First, lock the PID file */ pid_lockfile = fopen(pid_lockfilename.c_str(), "w"); @@ -263,7 +262,7 @@ void CreatePidFile(pid_t pid) if ( pid_lockfile ) { struct flock lock; - lock_fd = fileno(pid_lockfile); + int lock_fd = fileno(pid_lockfile); lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; diff --git a/src/utils/util_cstring.cc b/src/utils/util_cstring.cc index a4f0743c0..2f2c2ac38 100644 --- a/src/utils/util_cstring.cc +++ b/src/utils/util_cstring.cc @@ -191,15 +191,15 @@ int SnortStrnlen(const char* buf, int buf_size) */ const char* SnortStrnPbrk(const char* s, int slen, const char* accept) { - char ch; - const char* s_end; if (!s || (slen == 0) || !*s || !accept) return nullptr; - s_end = s + slen; + const char* s_end = s + slen; + while (s < s_end) { - ch = *s; + char ch = *s; + if (strchr(accept, ch)) return s; s++; @@ -214,16 +214,17 @@ const char* SnortStrnPbrk(const char* s, int slen, const char* accept) */ const char* SnortStrnStr(const char* s, int slen, const char* searchstr) { - char ch, nc; - int len; if (!s || (slen == 0) || !*s || !searchstr) return nullptr; + char ch; + if ((ch = *searchstr++) != 0) { - len = strlen(searchstr); + int len = strlen(searchstr); do { + char nc; do { if ((nc = *s++) == 0) @@ -235,6 +236,7 @@ const char* SnortStrnStr(const char* s, int slen, const char* searchstr) return nullptr; } while (nc != ch); + if (slen - len < 0) return nullptr; } @@ -249,18 +251,19 @@ const char* SnortStrnStr(const char* s, int slen, const char* searchstr) */ const char* SnortStrcasestr(const char* s, int slen, const char* substr) { - char ch, nc; - int len; - if (!s || (slen == 0) || !*s || !substr) return nullptr; + char ch; + if ((ch = *substr++) != 0) { ch = tolower((char)ch); - len = strlen(substr); + int len = strlen(substr); + do { + char nc; do { if ((nc = *s++) == 0) @@ -272,6 +275,7 @@ const char* SnortStrcasestr(const char* s, int slen, const char* substr) return nullptr; } while ((char)tolower((uint8_t)nc) != ch); + if (slen - len < 0) return nullptr; } diff --git a/src/utils/util_jsnorm.cc b/src/utils/util_jsnorm.cc index 76b84575d..72bc47c09 100644 --- a/src/utils/util_jsnorm.cc +++ b/src/utils/util_jsnorm.cc @@ -673,7 +673,6 @@ static void WriteDecodedSFCC(SFCCState* s) char* end = s->output.data + s->output.size; uint16_t len = s->output.len; char* ptr = s->output.data + len; - int copy_len = 0; if (ptr < end) { @@ -684,10 +683,13 @@ static void WriteDecodedSFCC(SFCCState* s) } else { + int copy_len = 0; + if ((end - ptr) < s->buflen) copy_len = end - ptr; else copy_len = s->buflen; + memcpy(ptr, s->buf, copy_len); ptr = ptr + copy_len; } @@ -797,17 +799,14 @@ static int SFCC_scan_fsm(SFCCState* s, int c) return(SFCC_exec(s, (ActionSFCC)m->action, c)); } -static void StringFromCharCodeDecode(const char* src, uint16_t srclen, const char** ptr, char** dst, +static void StringFromCharCodeDecode( + const char* src, uint16_t srclen, const char** ptr, char** dst, uint16_t* bytes_copied, JSState* js, uint8_t* iis_unicode_map) { - int iRet; - const char* start, * end; - SFCCState s; - uint16_t alert = 0; - - start = src; - end = src + srclen; + const char* start = src; + const char* end = src + srclen; + SFCCState s; s.buflen = 0; s.fsm = 0; s.output.data = decoded_out; @@ -817,7 +816,8 @@ static void StringFromCharCodeDecode(const char* src, uint16_t srclen, const cha while (!outBounds(start, end, *ptr)) { - iRet = SFCC_scan_fsm(&s, **ptr); + int iRet = SFCC_scan_fsm(&s, **ptr); + if (iRet != RET_OK) { if ( (iRet == RET_INV) && ((*ptr - 1) > start )) @@ -828,7 +828,7 @@ static void StringFromCharCodeDecode(const char* src, uint16_t srclen, const cha (*ptr)++; } - alert = s.alert_flags; + uint16_t alert = s.alert_flags; //alert mixed encodings if (alert != ( alert & -alert)) @@ -1062,14 +1062,10 @@ static int Unescape_scan_fsm(UnescapeState* s, int c, JSState* js) static void UnescapeDecode(const char* src, uint16_t srclen, const char** ptr, char** dst, uint16_t* bytes_copied, JSState* js, uint8_t* iis_unicode_map) { - int iRet; - const char* start, * end; - UnescapeState s; - uint16_t alert = 0; - - start = src; - end = src + srclen; + const char* start = src; + const char* end = src + srclen; + UnescapeState s; s.iNorm = 0; s.fsm = 0; s.output.data = decoded_out; @@ -1086,7 +1082,7 @@ static void UnescapeDecode(const char* src, uint16_t srclen, const char** ptr, c while (!outBounds(start, end, *ptr)) { - iRet = Unescape_scan_fsm(&s, **ptr, js); + int iRet = Unescape_scan_fsm(&s, **ptr, js); if (iRet != RET_OK) { /*if( (iRet == RET_INV) && ((*ptr - 1) > start )) @@ -1097,7 +1093,7 @@ static void UnescapeDecode(const char* src, uint16_t srclen, const char** ptr, c (*ptr)++; } - alert = s.alert_flags; + uint16_t alert = s.alert_flags; //alert mixed encodings if (alert != ( alert & -alert)) diff --git a/tools/snort2lua/preprocessor_states/pps_http_inspect.cc b/tools/snort2lua/preprocessor_states/pps_http_inspect.cc index 29075a0ba..94a004801 100644 --- a/tools/snort2lua/preprocessor_states/pps_http_inspect.cc +++ b/tools/snort2lua/preprocessor_states/pps_http_inspect.cc @@ -34,9 +34,6 @@ class HttpInspect : public ConversionState public: HttpInspect(Converter& c) : ConversionState(c) { } bool convert(std::istringstream& data) override; - -private: - bool add_decode_option(const std::string& opt_name, std::istringstream& stream); }; } // namespace @@ -130,25 +127,6 @@ bool HttpInspect::convert(std::istringstream& data_stream) return retval; } -bool HttpInspect::add_decode_option(const std::string& opt_name, std::istringstream& stream) -{ - int val; - - if (stream >> val) - { - table_api.open_table("decode"); - table_api.add_option(opt_name, val); - table_api.close_table(); - return true; - } - else - { - table_api.add_comment("snort.conf missing argument for " + - opt_name + " "); - return false; - } -} - /************************** ******* A P I *********** **************************/