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
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
* 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,
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);
*/
for ( plist=kt->patrn; plist; plist=plist->next )
{
- int shift, cindex;
-
for ( int k=0; k<kt->bcSize; 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 ] )
{
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 )
{
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;
for (; T <= Tend; n--, T++, Tx++ )
{
+ int tshift;
+
while ( (tshift = bcShift[ *( T + bcSize ) ]) > 0 )
{
T += tshift;
* 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))
} // 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<IcmpHdr*>(raw_pkt);
- updated_len += sizeof(*h);
+ updated_len += lyr_len;
if ( !(flags & UPD_COOKED) || (flags & UPD_REBUILT_FRAG) )
{
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)
{
{
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;
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
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;
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<NUM_RESERVED_LABELS)&&((iRet = checkMplsHdr(codec, label, bos)) < 0))
return false;
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<const GTPHdr*>(raw.data);
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)
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)
}
};
-TEST(file_connector_tinit_tterm, null)
-{
- CHECK(1==1);
-}
-
TEST(file_connector_tinit_tterm, alloc_discard)
{
const uint8_t* data = nullptr;
bool Found_Token = false;
uint8_t* Filter;
uint8_t Length;
- uint8_t c;
int Index;
fd_status_t Ret_Code = File_Decomp_OK;
for ( Index=0; Index<p->Filter_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) )
{
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 */
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' )
{
fd_PDF_Parse_p_t p = &(SessionPtr->PDF->Parse);
fd_status_t Ret_Code = File_Decomp_OK;
- uint8_t c;
while ( true )
{
return( File_Decomp_BlockOut );
/* Get next byte in input queue */
- c = *SessionPtr->Next_In;
+ uint8_t c = *SessionPtr->Next_In;
switch ( p->State )
{
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 ):
{
}
SessionPtr->PDF->State = PDF_STATE_PROCESS_STREAM;
- /* INTENTIONAL FALL-THROUGH INTO PDF_STATE_PROCESS_STREAM CASE. */
}
+ // fallthrough
case ( PDF_STATE_PROCESS_STREAM ):
{
}
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
#endif
SessionPtr->SWF->State = SWF_STATE_DATA;
- /* INTENTIONAL FALL-THROUGH INTO SWF_STATE_DATA CASE. */
}
+ // fallthrough
+
case ( SWF_STATE_DATA ):
{
Ret_Code = Decomp(SessionPtr);
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; i<node->num_children; i++ )
print_option_tree(node->children[i], level+1);
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 )
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;
}
state.last_check.result = result;
-
profile.stop(result != (int)IpsOption::NO_MATCH);
return result;
/* 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)
{
}
else
{
+ bool found_child_match = false;
+
if (child->option_data != option_data)
{
if (!node)
child = root->children[i];
if (child->option_data == option_data)
{
- found_child_match = 1;
+ found_child_match = true;
break;
}
}
child = node->children[i];
if (child->option_data == option_data)
{
- found_child_match = 1;
+ found_child_match = true;
break;
}
}
}
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;
}
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)
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))
{
/* 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);
}
}
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; i<len; i++, pos++)
{
if (pos == 17)
pos++;
fprintf(fp, "%s", " ");
}
- c = (char)data[i];
+ char c = (char)data[i];
+
if (isprint(c) and (c == ' ' or !isspace(c)))
str[pos] = c;
else
SnortConfig*, RateFilterConfig* rf_config, tSFRFConfigNode* cfgNode)
{
SFGHASH* genHash;
- int nrows;
- int hstatus;
tSFRFSidNode* pSidNode;
tSFRFConfigNode* pNewConfigNode;
tSFRFGenHashKey key = { 0,0 };
if ( !genHash )
{
+ int nrows;
+
if ( cfgNode->gid == 1 ) /* patmatch rules gid, many rules */
{
nrows= SFRF_GEN_ID_1_ROWS;
}
/* 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);
*/
void SFRF_ShowObjects(RateFilterConfig* config)
{
- SFGHASH* genHash;
tSFRFSidNode* pSidnode;
tSFRFConfigNode* cfgNode;
unsigned int gid;
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);
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;
THD_ITEM* sfthd_item;
THD_NODE* sfthd_node;
tThdItemKey key;
- int nrows;
- int hstatus;
PolicyId policy_id = get_network_policy()->policy_id;
/* 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;
}
/* 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);
*/
int sfthd_show_objects(ThresholdObjects* thd_objs)
{
- SFGHASH* sfthd_hash;
THD_ITEM* sfthd_item;
THD_NODE* sfthd_node;
unsigned gen_id;
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);
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.
// 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;
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);
}
break;
}
-
+ }
s_client_map = new ClientMap;
for ( int i=0; i<MAX_CLIENTS; i++ )
(*s_client_map)[i] = nullptr;
//-------------------------------------------------------------------------
struct SnortConfig;
+class Cursor;
enum CursorActionType
{
// packet threads
virtual bool is_relative() { return false; }
virtual bool fp_research() { return false; }
- virtual bool retry() { return false; }
+ virtual bool retry(Cursor&) { return false; }
virtual void action(Packet*) { }
enum EvalStatus { NO_MATCH, MATCH, NO_ALERT, FAILED_BIT };
- virtual EvalStatus eval(class Cursor&, Packet*) { return MATCH; }
+ virtual EvalStatus eval(Cursor&, Packet*) { return MATCH; }
option_type_t get_type() const { return type; }
const char* get_name() const { return name; }
*/
void sfghash_delete(SFGHASH* h)
{
- int i;
- SFGHASH_NODE* node, * onode;
-
if ( !h )
return;
if ( h->table )
{
- for (i=0; i<h->nrows; i++)
+ for (int i=0; i<h->nrows; 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 )
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;
}
int i;
SFXHASH* t;
SFXHASH_NODE* n;
- char strkey[256], strdata[256], * p;
+ char strkey[256], strdata[256];
int num = 100;
int mem = 0;
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);
}
TEST(sfghash, create_find_delete_test)
{
int i;
- char str[256], *p;
+ char str[256];
int num=100;
// Create a Hash Table
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)));
TEST(sfghash, collision_test)
{
int i;
- char str[256], * p;
+ char str[256];
int num=100;
// Create a Hash Table with smaller entries
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)));
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)
{
state = (fragment & 0x0fc) >> 2;
*p++ = b64(state);
state = (fragment & 0x003) << 4;
+ // fallthrough
case step_B:
if (data == data_end)
{
state |= (fragment & 0x0f0) >> 4;
*p++ = b64(state);
state = (fragment & 0x00f) << 2;
+ // fallthrough
case step_C:
if (data == data_end)
{
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;
{
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;
}
uint32_t value = 0;
- int payload_bytes_grabbed = 0;
+ int payload_bytes_grabbed = 0; // FIXIT-L reduce scope
if (!btd->data_string_convert_flag)
{
#include "profiler/profiler.h"
#include "utils/boyer_moore.h"
#include "utils/util.h"
+#include "utils/stats.h"
#include "extract.h"
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; }
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;
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;
}
static FLOWBITS_OBJECT* getFlowBitItem(char* flowbitName, FLOWBITS_OP* flowbits)
{
FLOWBITS_OBJECT* flowbits_item;
- int hstatus;
if (!validateName(flowbitName))
{
}
}
- 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);
static FLOWBITS_GRP* getFlowBitGroup(char* groupName)
{
- int hstatus;
FLOWBITS_GRP* flowbits_grp = nullptr;
if (!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);
static void FlowBitsVerify()
{
SFGHASH_NODE* n;
- FLOWBITS_OBJECT* fb;
unsigned num_flowbits = 0;
unsigned unchecked = 0, unset = 0;
n != nullptr;
n= sfghash_findnext(flowbits_hash))
{
- fb = (FLOWBITS_OBJECT*)n->data;
+ FLOWBITS_OBJECT* fb = (FLOWBITS_OBJECT*)n->data;
if (fb->toggle != flowbits_toggle)
{
{ return (config->options & SNORT_PCRE_RELATIVE) != 0; }
EvalStatus eval(Cursor&, Packet*) override;
- bool retry() override;
+ bool retry(Cursor&) override;
PcreData* get_data()
{ return config; }
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<expression_len; i+=4)
{
- tmp = 0;
- k = expression_len - i;
+ uint32_t tmp = 0;
+ int k = expression_len - i;
+
if (k > 4)
k=4;
- for (l=0; l<k; l++)
+ for (int l=0; l<k; l++)
{
- tmp |= *(data->expression + i + l) << l*8;
+ tmp |= *(config->expression + i + l) << l*8;
}
switch (j)
mix(a,b,c);
}
- a += data->options;
+ a += config->options;
mix_str(a,b,c,get_name());
finalize(a,b,c);
// 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)))
{
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; }
return NO_MATCH;
}
-bool RegexOption::retry()
+bool RegexOption::retry(Cursor&)
{
return !is_relative();
}
*/
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;
sum = 0;
for (i = digits - 1; i >= 0; i--)
{
- val = cc_digits[i] - '0';
+ int val = cc_digits[i] - '0';
if (alternate)
{
val *= 2;
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)
CHECK(opt->is_relative());
CHECK(opt->eval(c, &pkt) == IpsOption::NO_MATCH);
- CHECK(!opt->retry());
+ CHECK(!opt->retry(c));
}
//-------------------------------------------------------------------------
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() )
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);
*/
void WarningMessage(const char* format,...)
{
- char buf[STD_BUF+1];
va_list ap;
if ( snort_conf and SnortConfig::log_quiet() )
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);
*/
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);
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];
static OptTreeNode* OptTreeNode_Search(uint32_t, uint32_t sid)
{
SFGHASH_NODE* hashNode;
- OptTreeNode* otn = nullptr;
- RuleTreeNode* rtn = nullptr;
if (sid == 0)
return nullptr;
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) )
{
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;
}
// 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) )
{
void CodecManager::instantiate(CodecApiWrapper& wrap, Module* m, SnortConfig*)
{
- static std::size_t codec_id = 1;
-
if (!wrap.init)
{
std::vector<ProtocolId> 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");
Codec* cd = cd_api->ctor(m);
cd->get_protocol_ids(ids);
+
for (auto id : ids)
{
if (s_proto_map[to_utype(id)] != 0)
s_protocols[s_proto_map[to_utype(id)]]->get_name(), cd->get_name(),
static_cast<uint16_t>(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;
#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"
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);
}
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;
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))
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;
}
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;
void MimeDecode::process_decode_type(const char* start, int length, bool cnt_xf,
MimeStats* mime_stats)
{
- const char* tmp = nullptr;
-
if (decoder)
delete decoder;
{
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)
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)
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)
while (ptr < data_end_marker)
{
- int header_name_len;
int max_header_name_len = 0;
get_mime_eol(ptr, data_end_marker, &eol, &eolm);
}
/* 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;
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;
#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])
{
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]);
}
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]);
{
int i = 1;
char* p;
- RNAIpAddrSet* ias;
RNAIpv6AddrSet* ias6;
IpProtocol proto;
unsigned long dir;
}
else
{
- ias = ParseIpCidr(toklist[i], app_id_netmasks);
+ RNAIpAddrSet* ias = ParseIpCidr(toklist[i], app_id_netmasks);
if (!ias || ias->addr_flags)
{
if (ias)
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; )
/* scan for comments */
while (i < argcount)
{
- tok = toklist[i];
+ char* tok = toklist[i];
if (tok[0] == '#' && !drop_further)
{
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))
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++;
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);
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;
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)
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);
}
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)
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)
{
}
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)
tPatternList* newNode;
const tMlpPattern* nextPattern;
const tMlpPattern* patterns = *inputPatternList;
- int rvalue;
if (!rootNode || !patterns || !patterns->pattern)
return -1;
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);
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:
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:
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;
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);
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:
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;
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<char*>(snort_calloc(host_len + 1)); // plus '\0' at end
+ const uint8_t* src = host;
+ char* dst = str;
+
uint32_t dstLen = 0;
- str = static_cast<char*>(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
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();
}
{
char* p = fd->username;
char* p_end = p + sizeof(fd->username) - 1;
- int found_tick = 0;
if (*s == '"')
{
}
else
{
+ bool found_tick = false;
+
for (; s < end && p < p_end; s++)
{
if (isalnum(*s) || *s == '.' || *s == '@' || *s == '-' || *s == '_')
}
}
else if (*s == '`')
- found_tick = 1;
+ found_tick = true;
else if (*s == ' ')
{
fd->count++;
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)
{
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();
}
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:
static inline void free_matched_patterns(MatchedPatterns* mp)
{
- MatchedPatterns* tmp;
-
while (mp)
{
- tmp = mp;
+ MatchedPatterns* tmp = mp;
mp = mp->next;
snort_free(tmp);
}
{
MatchedCHPAction* insert_sweep2 = nullptr;
bool inhibit_modify = false;
- CHPAction* match = nullptr;
AppId ret = APP_ID_NONE;
unsigned pt = cmd.cur_ptype;
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)
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)
{
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;
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;
&& 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++)
#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"
{
int i;
const char* str_ptr;
- uint16_t length;
LengthKey length_sequence;
int index = 1;
}
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\")!",
assert(!ldp.pkt);
}
+#ifdef NDEBUG
+ UNUSED(ldp);
+#endif
+
return true;
}
{
// FIXIT-L make these perf counters
size_t totalMem = 0;
- size_t mem;
if ( allocated_detectors.empty() )
return;
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);
}
/* 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]; p<end && *p && *p!='('; p++)
if (p < end)
{
p++;
- ven = p;
+ const unsigned char* ven = p;
+
for (; p<end && *p && *p!=' '; p++)
;
if (p < end && *p)
MDNS User Analysis*/
int MdnsServiceDetector::analyze_user(AppIdSession* asd, const Packet* pkt, uint16_t size)
{
- char user_name[MAX_LENGTH_SERVICE_NAME] = "";
- const char* user_name_bkp = nullptr;
int start_index = 0;
- int processed_ans = 0;
uint8_t user_name_len = 0;
uint16_t data_size = size;
const char* srv_original = (const char*)pkt->data + 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
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;
}
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';
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)
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)
/* 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;
const NBNSLabelData* lbl_data;
const NBNSLabelPtr* lbl_ptr;
int i;
- int j;
if (end - *data < (int)sizeof(NBNSLabelLength))
return -1;
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);
const uint8_t* const end)
{
int ret;
- uint16_t tmp;
ret = netbios_validate_name(data, begin, end);
if (ret)
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;
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;
{
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;
{
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)
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);
return APPID_INPROCESS;
}
*program = rd->program;
+ const ServiceRPCPortmapReply* pmr = nullptr;
+
switch (rd->program)
{
case RPC_PROGRAM_PORTMAP:
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)
AppId* ClientAppId, AppId* payloadId)
{
MatchedSSLPatterns* mp = nullptr;
- MatchedSSLPatterns* tmpMp;
SSLCertPattern* best_match;
if (!matcher)
best_match = mp->mpattern;
}
}
- tmpMp = mp;
+ MatchedSSLPatterns* tmpMp = mp;
mp = mp->next;
snort_free(tmpMp);
}
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;
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 )
p->packet_flags |= PKT_MODIFIED;
return 1;
}
- if ( p->packet_flags & PKT_RESIZED )
+ if ( p->packet_flags & (PKT_RESIZED|PKT_MODIFIED) )
{
return 1;
}
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<DAQ_PktHdr_t*>(p->pkth))->pktlen = (len < ETH_MIN_LEN) ? ETH_MIN_LEN : len;
+ (const_cast<DAQ_PktHdr_t*>(p->pkth))->pktlen =
+ (len < ETH_MIN_LEN) ? ETH_MIN_LEN : len;
+
p->packet_flags |= PKT_RESIZED;
changes++;
}
FlowStateValue* FlowIPTracker::find_stats(const SfIp* src_addr, const SfIp* dst_addr,
int* swapped)
{
- SFXHASH_NODE* node;
FlowStateKey key;
FlowStateValue* value;
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,
int ipset_print(IPSET* ipc)
{
- char ip_str[80];
- PORTRANGE* pr;
-
if ( !ipc )
return 0;
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) )
{
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;
unsigned host, mask, not_flag;
PORTSET portset;
char** curip;
- int ret;
IPADDRESS* adp;
char* ips[] =
{
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);
}
}
/* 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);
}
void test_ip4set_parsing()
{
char** curip;
- int ret;
char* ips[] =
{
"12.24.24.1/32,!24.24.24.1",
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);
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;
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)
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");
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;
}
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;
if (maxPayload)
{
+ uint16_t toSend;
do
{
plen = 0;
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()
*/
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++;
static PortObject* _POParsePort(POParser* pop)
{
- uint16_t hport, lport;
- char c;
PortObject* po = PortObjectNew();
if (!po)
return nullptr;
}
- pop->token[0]=0;
+ pop->token[0] = 0;
/* The string in pop should only be of the form <port> or <port>:<port> */
- lport = POParserGetShort(pop);
+ uint16_t lport = POParserGetShort(pop);
if (pop->errflag)
{
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 == ','))
int proto, FastPatternConfig* fp)
{
int large_port_group = 0;
- int src_cnt = 0;
- int dst_cnt = 0;
PortTable* dstTable;
PortTable* srcTable;
PortObject* aaObject;
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);
static void FreeRuleTreeNodes(SnortConfig* sc)
{
RuleTreeNode* rtn;
- OptTreeNode* otn;
PolicyId policyId;
SFGHASH_NODE* hashNode;
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 */
void FreeRuleTreeNode(RuleTreeNode* rtn)
{
- RuleFpList* idx, * tmp;
if (!rtn)
return;
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);
}
int i;
int evalIndex = 0;
RuleListNode* ordered_list = nullptr;
- RuleListNode* prev;
RuleListNode* node;
char** toks;
int num_toks;
for ( i = 0; i < num_toks; i++ )
{
- prev = nullptr;
+ RuleListNode* prev = nullptr;
node = sc->rule_lists;
while (node != nullptr)
*/
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 )
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, '$'))
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 == '"')
{
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] == '(')
{
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);
*/
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;
/* 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);
/* 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);
}
*/
PortObject* PortObjectDupPorts(PortObject* po)
{
- PortObjectItem* poi = nullptr;
- PortObjectItem* poinew = nullptr;
SF_LNODE* lpos = nullptr;
-
PortObject* ponew = PortObjectNew();
+
if ( !ponew )
return nullptr;
/* 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);
*/
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;
*/
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;
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;
/* 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;
}
/* 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;
}
}
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);
#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)
{
GetProfileFromFunction functor("foo", s_profiler_stats_getter);
CHECK( functor() == &the_stats );
+
+ s_profiler_stats = nullptr;
}
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;
}
}
#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
// 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 )
}
// 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<DAQ_PktHdr_t*>(p->pkth);
pkth->caplen = len;
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)
/* 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;
* 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)
{
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;
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;
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;
/* 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)
{
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;
/* 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 */
/* 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 */
*/
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;
/* 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
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;
}
/* 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 )
queue_array[s] = true;
}
int fs = FailState[r];
+ int next;
/*
* Locate the next valid state for 'i' starting at fs
*/
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; k<acsm->acsmNumStates; k++)
+ for (int k=0; k<acsm->acsmNumStates; 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++;
}
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;
*/
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; k<acsm->acsmNumStates; k++)
+ for (int k=0; k<acsm->acsmNumStates; 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 )
{
}
/* 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];
}
*/
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; i<asize; i++ )
+ for ( int i=0; i<asize; i++ )
{
- state = next[i];
+ acstate_t state = next[i];
if ( state !=0 && state != ACSM_FAIL_STATE2 )
{
begin[nbands] = i;
- zcnt=0;
+ int zcnt=0;
+
for (; i< asize; i++ )
{
state = next[i];
*/
static int Conv_Full_DFA_To_SparseBands(ACSM_STRUCT2* acsm)
{
- acstate_t* p;
acstate_t** NextState = acsm->acsmNextState;
- 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; k<acsm->acsmNumStates; k++)
+ for (int k=0; k<acsm->acsmNumStates; 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<nbands; i++)
+ int cnt = 3;
+
+ for (int i=0; i<nbands; i++)
{
cnt += 2;
cnt += band_end[i] - band_begin[i] + 1;
cnt=%d\n",k,i,band_begin[i],band_end[i],band_end[i]-band_begin[i]+1); */
}
- p = (acstate_t*)AC_MALLOC_DFA(sizeof(acstate_t)*(cnt), sizeof(acstate_t));
+ acstate_t* p = (acstate_t*)AC_MALLOC_DFA(sizeof(acstate_t)*(cnt), sizeof(acstate_t));
if (!p)
return -1;
- m = 0;
+ int m = 0;
p[m++] = ACF_SPARSE_BANDS;
p[m++] = 0; /* no matches */
p[m++] = nbands;
- for ( i=0; i<nbands; i++ )
+ for ( int i=0; i<nbands; i++ )
{
p[m++] = band_end[i] - band_begin[i] + 1; /* # states in this band */
p[m++] = band_begin[i]; /* start index */
- for ( j=band_begin[i]; j<=band_end[i]; j++ )
+ for ( int j=band_begin[i]; j<=band_end[i]; j++ )
{
if (j >= MAX_ALPHABET_SIZE)
{
*/
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 */
{
case ACF_BANDED:
{
- n = ps[0];
- index = ps[1];
+ acstate_t n = ps[0];
+ unsigned index = ps[1];
if ( input < index )
{
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-- )
{
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 )
{
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:
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-- )
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;
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] )
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)
{
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;
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)
{
#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;k<acsm->acsmNumStates;k++)
- {
- p = NextState[k];
+ for (int k=0; k<acsm->acsmNumStates; 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; i<nb; i++)
+ {
+ acstate_t n = *p++;
+ fwrite(&n, sizeof(acstate_t), 1, fp);
- for(i=0;i<nb;i++)
- {
- 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), 1, fp);
+ }
+ }
+ else if ( fmt == ACF_FULL )
+ {
+ fwrite(p, sizeof(acstate_t), acsm->acsmAlphabetSize, 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(
#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 )
{
#if 0
int cnt=0;
#endif
- int k, fs, fr;
bnfa_state_t* FailState = bnfa->bnfaFailState;
- for (k=2; k<bnfa->bnfaNumStates; k++)
+ for (int k=2; k<bnfa->bnfaNumStates; k++)
{
- fr = fs = FailState[k];
+ int fs = FailState[k];
+ int fr = fs;
+
while ( fs && KcontainsJ(bnfa->bnfaTransTable[k],bnfa->bnfaTransTable[fs]) )
{
fs = FailState[fs];
#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; i<bnfa->bnfaAlphabetSize; i++ )
+ for ( int i=0; i<bnfa->bnfaAlphabetSize; i++ )
{
- state = p[i];
+ bnfa_state_t state = p[i];
if ( state != 0 && state != BNFA_FAIL_STATE )
{
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));
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)
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];
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 )
{
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];
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 )
{
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];
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 )
{
*/
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 )
{
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 (; T<Tend; T++)
{
- Tchar = xlatcase[ *T ];
+ uint8_t Tchar = xlatcase[ *T ];
/* Transition to next state index */
sindex = _bnfa_get_next_state_csparse_nfa(transList,sindex,Tchar);
last_match = sindex;
{
- mlist = MatchList[ transList[sindex] ];
+ bnfa_match_node_t* mlist = MatchList[ transList[sindex] ];
+
if ( !mlist )
return nfound;
- 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,
+ int res = match(patrn->userdata, mlist->rule_option_tree, index,
context, mlist->neg_list);
if ( res > 0 )
{
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 (; T<Tend; T++)
{
- Tchar = xlatcase[ *T ];
+ uint8_t Tchar = xlatcase[ *T ];
/* Transition to next state index */
sindex = _bnfa_get_next_state_csparse_nfa(transList,sindex,Tchar);
last_match = sindex;
{
- mlist = MatchList[ transList[sindex] ];
- patrn = (bnfa_pattern_t*)mlist->data;
- 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 )
{
{
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_index<BO_MAGIC_SIZE; cookie_index++)
+ for (int cookie_index=0; cookie_index<BO_MAGIC_SIZE; cookie_index++)
{
cookie_cyphertext[cookie_index] =(uint8_t)(*cp_ptr^(BoRand()));
cp_ptr++;
* generate the key lookup mechanism from the first 2 characters of
* the cyphertext
*/
+ uint16_t cyphertext_referent;
cyphertext_referent = (uint16_t)(cookie_cyphertext[0] << 8) & 0xFF00;
cyphertext_referent |= (uint16_t)(cookie_cyphertext[1]) & 0x00FF;
void DceHttpProxy::clear(Packet* p)
{
Flow* flow = p->flow;
- 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++;
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++;
// 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:
break;
}
-
- // Fall through for Windows 2000 for first request to file
+ // fallthrough
case DCE2_POLICY__WIN2003:
case DCE2_POLICY__WINXP:
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)
{
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)
{
int PrintFTPServerConf(FTP_SERVER_PROTO_CONF* ServerConf)
{
- char buf[BUF_SIZE+1];
int iRet;
FTP_CMD_CONF* FTPCmd;
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)
#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 )
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) &&
{
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;
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)))
{
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)
/* 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); );
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];
********************************************************************/
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"); );
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)
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)))
{
* 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*/
********************************************************************/
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
// 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*/
********************************************************************/
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<length; i+=4)
{
- tmp = 0;
- k = length - i;
+ uint32_t tmp = 0;
+ int k = length - i;
+
if (k > 4)
k=4;
- for (l=0; l<k; l++)
+ for (int l=0; l<k; l++)
{
tmp |= *(str + i + l) << l*8;
}
static void SMTP_PrintConfig(SMTP_PROTO_CONF *config)
{
- const SMTPToken* cmd;
+ assert(config);
+
char buf[8192];
- int max_line_len_count = 0;
- int max_line_len = 0;
int alert_count = 0;
- if (config == nullptr)
- return;
-
- memset(&buf[0], 0, sizeof(buf));
-
LogMessage("SMTP Config:\n");
snprintf(buf, sizeof(buf) - 1, " Normalize: ");
if(config->normalize == 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)
{
{
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)
{
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)
{
*
* @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)
{
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)
}
#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 != '-')))
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);
* 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);
}
}
*/
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))
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;
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)
{
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();
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; index<NUM_IPS; index++)
+ for (uint32_t index=0; index<NUM_IPS; index++)
{
ip_list[index] = (uint32_t)rand()%NUM_IPS;
data[index%NUM_DATA] = index%26 + 65; /* Random letter */
}
- dir = sfrt_new(DIR_16x2, IPv4, NUM_IPS, 20);
+ table_t* dir = sfrt_new(DIR_16x2, IPv4, NUM_IPS, 20);
if (!dir)
{
return 1;
}
- for (index=0; index < NUM_IPS; index++)
+ for (uint32_t index=0; index < NUM_IPS; index++)
{
if (sfrt_insert(&ip_list[index], 32, &data[index%NUM_DATA],
RT_FAVOR_SPECIFIC, dir) != RT_SUCCESS)
data[index%NUM_DATA], *(uint32_t*)sfrt_lookup(&ip_list[index], dir));
}
- for (index=0; index < NUM_IPS; index++)
+ for (uint32_t index=0; index < NUM_IPS; index++)
{
- val = *(uint32_t*)sfrt_lookup(&ip_list[index], dir);
+ uint32_t val = *(uint32_t*)sfrt_lookup(&ip_list[index], dir);
printf("\t@%u\t%x: %c. originally:\t%c\n",
index, ip_list[index], val, data[index%NUM_DATA]);
}
/* Create new dir-n-m root table with 'count' depth */
dir_table_t* sfrt_dir_new(uint32_t mem_cap, int count,...)
{
- va_list ap;
- uint32_t val;
- int index;
-
dir_table_t* table = (dir_table_t*)snort_alloc(sizeof(dir_table_t));
table->allocated = 0;
table->dimensions = (int*)snort_alloc(sizeof(int)*count);
table->dim_size = count;
+ va_list ap;
va_start(ap, count);
- for (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);
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. */
/* 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);
dir_sub_table_t* sub_table, dir_table_t* root_table)
{
word index;
- uint32_t fill;
uint32_t valueIndex = 0;
{
/* 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);
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;
for (index=0; index < count; index++)
{
- val = va_arg(ap, int);
+ uint32_t val = va_arg(ap, int);
table->dimensions[index] = val;
}
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]);
/* 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);
void TcpStreamTracker::cache_mac_address(TcpSegmentDescriptor& tsd, uint8_t direction)
{
- int i;
-
/* Not Ethernet based, nothing to do */
if ( tsd.get_pkt()->is_eth() )
{
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];
}
{
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;
}
if ( px.idx > idx )
{
- shift = px.idx - idx;
+ uint32_t shift = px.idx - idx;
if ( shift > len )
shift = len;
data += shift;
/* 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;
{
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);
}
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( );
}
{
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
listener->compare_mac_addresses(eh->ether_src) ) )
return;
+ uint32_t event_code = 0;
+
if ( t_hijack )
{
if ( p->is_from_client() )
HostAttributeEntry* host_entry;
ApplicationEntry* service;
unsigned service_count = 0;
- int rval;
host_entry = (HostAttributeEntry*)sfrt_lookup(ipAddr, curr_cfg->lookupTable);
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;
*/
static int KMapFreeNodeList(KMAP* km)
{
- KEYNODE* k, * kold;
-
- for ( k=km->keylist; k; )
+ for ( KEYNODE* k=km->keylist; k; )
{
if ( k->key )
{
{
km->userfree(k->userdata);
}
- kold = k;
+ KEYNODE* kold = k;
k = k->next;
snort_free(kold);
}
*/
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);
}
*/
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 )
{
xkey.resize(n);
- for (i=0; i<n; i++)
+ for (int i=0; i<n; i++)
xkey[i] = std::tolower(P[i]);
P = (const unsigned char*)xkey.c_str();
}
/* Save key size */
- ksize = n;
+ int ksize = n;
+ KMAPNODE* root;
//printf("adding key='%.*s'\n",n,P);
*/
void* KMapFind(KMAP* ks, void* key, int n)
{
- const unsigned char* T = (unsigned char*)key;
- KMAPNODE* root;
- int i;
std::string xkey;
+ const unsigned char* T = (unsigned char*)key;
if ( n <= 0 )
{
if ( ks->nocase )
{
xkey.resize(n);
- for (i=0; i<n; i++)
+
+ for (int i=0; i<n; i++)
xkey[i] = std::tolower(T[i]);
T = (const unsigned char*)xkey.c_str();
//printf("finding key='%.*s'\n",n,T);
/* Check if any keywords start with this character */
- root = ks->root[ *T ];
+ KMAPNODE* root = ks->root[ *T ];
if ( !root )
return nullptr;
*/
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);
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);
{
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");
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;
*/
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++;
*/
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)
return nullptr;
}
while (nc != ch);
+
if (slen - len < 0)
return nullptr;
}
*/
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)
return nullptr;
}
while ((char)tolower((uint8_t)nc) != ch);
+
if (slen - len < 0)
return nullptr;
}
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)
{
}
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;
}
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;
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 ))
(*ptr)++;
}
- alert = s.alert_flags;
+ uint16_t alert = s.alert_flags;
//alert mixed encodings
if (alert != ( alert & -alert))
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;
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 ))
(*ptr)++;
}
- alert = s.alert_flags;
+ uint16_t alert = s.alert_flags;
//alert mixed encodings
if (alert != ( alert & -alert))
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
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 + " <int>");
- return false;
- }
-}
-
/**************************
******* A P I ***********
**************************/