Overhauling the internal reporting of messages to the user.

The Logger class is now in charge of reporting all errors, warnings,
informational messages, weirds, and syslogs. All other components
route their messages through the global bro_logger singleton.

The Logger class comes with these reporting methods:

    void Message(const char* fmt, ...);
    void Warning(const char* fmt, ...);
    void Error(const char* fmt, ...);
    void FatalError(const char* fmt, ...); // Terminate Bro.
    void Weird(const char* name);
    [ .. some more Weird() variants ... ]
    void Syslog(const char* fmt, ...);
    void InternalWarning(const char* fmt, ...);
    void InternalError(const char* fmt, ...); // Terminates Bro.

See Logger.h for more information on these.

Generally, the reporting now works as follows:

    - All non-fatal message are reported in one of two ways:

        (1) At startup (i.e., before we start processing packets),
            they are logged to stderr.

        (2) During processing, they turn into events:

            event log_message%(msg: string, location: string%);
            event log_warning%(msg: string, location: string%);
            event log_error%(msg: string, location: string%);

            The script level can then handle them as desired.

            If we don't have an event handler, we fall back to
            reporting on stderr.

    - All fatal errors are logged to stderr and Bro terminates
      immediately.

    - Syslog(msg) directly syslogs, but doesn't do anything else.

The three main types of messages can also be generated on the
scripting layer via new Log::* bifs:

    Log::error(msg: string);
    Log::warning(msg: string);
    Log::message(msg: string);

These pass through the bro_logger as well and thus are handled in the
same way. Their output includes location information.

More changes:

    - Removed the alarm statement and the alarm_hook event.

    - Adapted lots of locations to use the bro_logger, including some
      of the messages that were previously either just written to
      stdout, or even funneled through the alarm mechanism.

    - No distinction anymore between Error() and RunTime(). There's
      now only one class of errors; the line was quite blurred already
      anyway.

    - util.h: all the error()/warn()/message()/run_time()/pinpoint()
      functions are gone. Use the bro_logger instead now.

    - Script errors are formatted a bit differently due to the
      changes. What I've seen so far looks ok to me, but let me know
      if there's something odd.

Notes:

    - The default handlers for the new log_* events are just dummy
      implementations for now since we need to integrate all this into
      the new scripts anyway.

    - I'm not too happy with the names of the Logger class and its
      instance bro_logger. We now have a LogMgr as well, which makes
      this all a bit confusing. But I didn't have a good idea for
      better names so I stuck with them for now.

      Perhaps we should merge Logger and LogMgr?
This commit is contained in:
Robin Sommer 2011-06-24 21:33:05 -07:00
parent ff7b92ffc8
commit 93894eed9b
140 changed files with 2453 additions and 1054 deletions

@ -1 +1 @@
Subproject commit 4fc13f7c6987b4163609e3df7a31f38501411cb7
Subproject commit 43994f50b320ff9e1d129b87bbe3a26dbfb3e33d

@ -1 +1 @@
Subproject commit 1a610bced1c83644a5bfaeb6e98cf75380fe61a1
Subproject commit 3ec53f69fd45d8e2c0950dc0e7af117bb3e02c0d

@ -1 +1 @@
Subproject commit 8843da57dc8aee433550727dcbd1199824ca9da4
Subproject commit 6022b88bbceaf16ff80aa323901c5d793115ba99

@ -1 +1 @@
Subproject commit ad9528f6795f104db8ec2f1425fc0b69d77ab92d
Subproject commit c3f7167a562689eba71ea72f17ca179abed4a191

@ -1 +1 @@
Subproject commit a9aeb2e1a8434c583c75f5941b58dc69a7517444
Subproject commit 0b92f854c80e7903f2c2e74891cb71f5cac4b3ed

View file

@ -1,3 +0,0 @@
# $Id: alarm.bro 340 2004-09-09 06:38:27Z vern $
redef bro_alarm_file = open_log_file("alarm");

View file

@ -1,7 +1,6 @@
@load heavy-analysis
@load OS-fingerprint
@load adu
@load alarm
@load analy
@load anon
@load arp

View file

@ -288,8 +288,6 @@ type entropy_test_result: record {
@load logging # sic! Not logging.bif.
@load logging-ascii
global bro_alarm_file: file &redef;
global alarm_hook: function(msg: string): bool &redef;
global log_file_name: function(tag: string): string &redef;
global open_log_file: function(tag: string): file &redef;
@ -1559,3 +1557,18 @@ const skip_http_data = F &redef;
# Whether the analysis engine parses IP packets encapsulated in
# UDP tunnels. See also: udp_tunnel_port, policy/udp-tunnel.bro.
const parse_udp_tunnels = F &redef;
event log_message(t: time, msg: string, location: string)
{
print fmt("[script] log_message: %s [%s] [%.6f]", msg, location, t);
}
event log_warning(t: time, msg: string, location: string)
{
print fmt("[script] log_warning: %s [%s] [%.6f]", msg, location, t);
}
event log_error(t: time, msg: string, location: string)
{
print fmt("[script] log_error: %s [%s] [%.6f]", msg, location, t);
}

View file

@ -14,7 +14,6 @@
@load site
@load backdoor
@load alarm
@load weird
# By default, do backdoor detection on everything except standard HTTP

View file

@ -4,7 +4,6 @@
# General policy - these scripts are more infrastructural than service
# oriented, so in general avoid changing anything here.
@load alarm # open logging file for alarm events
# Set global constant. This can be used in ifdef statements to determine
# if signatures are enabled.

View file

@ -190,6 +190,6 @@ redef notice_policy += {
};
@endif
# Use tagged log files for alarms and notices.
# Use tagged log files for notices.
redef use_tagging = T;

View file

@ -46,7 +46,7 @@ event bro_init()
{
# Disable packet processing.
install_src_net_filter(0.0.0.0/0, 0, 100);
alarm "waiting for hand-over - packet processing disabled.";
# Log::message("waiting for hand-over - packet processing disabled.");
}
event remote_connection_error(p: event_peer, reason: string)
@ -55,7 +55,7 @@ event remote_connection_error(p: event_peer, reason: string)
return;
# Seems that the other side in not running.
alarm "can't connect for hand-over - starting processing ...";
# Log::error("can't connect for hand-over - starting processing ...");
handover_start_processing();
}
@ -72,7 +72,7 @@ event remote_connection_established(p: event_peer)
if ( ! is_handover_peer(p) )
return;
alarm fmt("requesting hand-over from %s:%d", p$host, p$p);
# Log::message(fmt("requesting hand-over from %s:%d", p$host, p$p));
request_remote_events(p, /handover_.*|finished_send_state/);
@ -85,7 +85,7 @@ event remote_connection_established(p: event_peer)
# if the remote host is defined as a hand-over host in remote_peers.
if ( is_handover_peer(p) )
{
alarm fmt("allowing hand-over from %s:%d", p$host, p$p);
# Log::message(fmt("allowing hand-over from %s:%d", p$host, p$p));
request_remote_events(p, /handover_.*|finished_send_state/);
}
}
@ -99,7 +99,7 @@ event handover_send_state(p: event_peer)
# we will have to try again.
if ( ! send_state(p) )
{
alarm "can't send state; serialization in progress";
# Log::message("can't send state; serialization in progress");
schedule 5 secs { handover_send_state(p$host, p$p) };
}
}
@ -124,8 +124,8 @@ event finished_send_state(p: event_peer)
if ( ! is_handover_peer(p) )
return;
alarm fmt("full state received from %s:%d - starting processing ...",
p$host, p$p);
#Log::message(fmt("full state received from %s:%d - starting processing ...",
# p$host, p$p));
event handover_got_state(p);
@ -139,6 +139,6 @@ event handover_got_state(p: event_peer)
if ( ! (is_remote_event() && is_it_us(p$host, p$p)) )
return;
alarm fmt("%s:%d received our state - terminating", p$host, p$p);
# Log::message(fmt("%s:%d received our state - terminating", p$host, p$p));
terminate();
}

View file

@ -85,7 +85,7 @@ function check_spoof(c: connection): bool
service !in allow_spoof_services )
{
if ( c$id$orig_p == service && orig == resp )
event conn_weird("Land_attack", c);
event conn_weird("Land_attack", c, "");
if ( same_local_net_is_spoof )
++c$hot;

View file

@ -53,8 +53,8 @@ event http_message_done(c: connection, is_orig: bool, stat: http_message_stat)
# This can happen for multipart messages with a
# 'content-length' header, which is not required for multipart
# messages.
alarm fmt("length mismatch: %s %d %d %d",
id_string(c$id), stat$body_length, msg$data_length,
stat$content_gap_length);
# Log::warning(fmt("length mismatch: %s %d %d %d",
# id_string(c$id), stat$body_length, msg$data_length,
# stat$content_gap_length));
}
}

View file

@ -133,6 +133,11 @@ export {
global flush: function(id: ID): bool;
global add_default_filter: function(id: ID) : bool;
global remove_default_filter: function(id: ID) : bool;
# Defined in logging.bif.
# global message: function(msg: string) : bool;
# global warning: function(msg: string) : bool;
# global error: function(msg: string) : bool;
}
# We keep a script-level copy of all filters so that we can manipulate them.
@ -206,4 +211,3 @@ function remove_default_filter(id: ID) : bool
{
return remove_filter(id, "default");
}

View file

@ -1,6 +1,5 @@
# $Id: mt.bro 340 2004-09-09 06:38:27Z vern $
@load alarm
@load dns-lookup
@load hot
@load frag

View file

@ -373,7 +373,7 @@ function NOTICE(n: notice_info)
{
if ( use_tagging )
{
alarm info;
# alarm info;
event notice_alarm(n, action);
}
else
@ -390,7 +390,7 @@ function NOTICE(n: notice_info)
n$src_peer$p);
}
alarm fmt("%s %s%s", n$note, descr, n$msg);
# alarm fmt("%s %s%s", n$note, descr, n$msg);
event notice_alarm(n, action);
}
}

View file

@ -1,6 +1,6 @@
# $Id:$
#
# Forward remote alarms to our local system.
# Forward remote notices to our local system.
event notice_action(n: notice_info, action: NoticeAction)
{

View file

@ -2,7 +2,6 @@
@load signatures
@load software
@load alarm
redef signature_files += "ssl-worm.sig";

View file

@ -4,7 +4,6 @@
@load port-name
@load demux
@load login
@load alarm
module Stepping;

View file

@ -147,7 +147,7 @@ function check_TRW_scan(c: connection, state: string, reverse: bool): bool
theta_one >= 1 || theta_one >= theta_zero )
{
# Error: theta_zero should be between 0 and 1.
alarm "bad theta_zero/theta_one in check_TRW_scan";
# Log::error("bad theta_zero/theta_one in check_TRW_scan");
use_TRW_algorithm = F;
return F;
}
@ -169,7 +169,7 @@ function check_TRW_scan(c: connection, state: string, reverse: bool): bool
target_false_positive_prob >= 1 )
{
# Error: target probabilities should be between 0 and 1
alarm "bad target probabilities in check_TRW_scan";
# Log::error("bad target probabilities in check_TRW_scan");
use_TRW_algorithm = F;
return F;
}

View file

@ -372,12 +372,7 @@ function report_weird_orig(t: time, name: string, id: string, orig: addr)
report_weird(t, name, id, F, "", action, no_log);
}
event conn_weird(name: string, c: connection)
{
report_weird_conn(network_time(), name, weird_id_string(c$id), "", c);
}
event conn_weird_addl(name: string, c: connection, addl: string)
event conn_weird(name: string, c: connection, addl: string)
{
report_weird_conn(network_time(), name, weird_id_string(c$id), addl, c);
}

View file

@ -5,6 +5,7 @@
#include "ARP.h"
#include "Event.h"
#include "Logger.h"
ARP_Analyzer::ARP_Analyzer()
@ -218,12 +219,7 @@ void ARP_Analyzer::BadARP(const struct arp_pkthdr* hdr, const char* msg)
void ARP_Analyzer::Corrupted(const char* msg)
{
if ( ! net_weird )
return;
val_list* vl = new val_list;
vl->append(new StringVal(msg));
mgr.QueueEvent(net_weird, vl);
bro_logger->Weird(msg);
}
void ARP_Analyzer::RREvent(EventHandlerPtr e,

View file

@ -916,12 +916,12 @@ void TransportLayerAnalyzer::Done()
void TransportLayerAnalyzer::SetContentsFile(unsigned int /* direction */,
BroFile* /* f */)
{
run_time("analyzer type does not support writing to a contents file");
bro_logger->Error("analyzer type does not support writing to a contents file");
}
BroFile* TransportLayerAnalyzer::GetContentsFile(unsigned int /* direction */) const
{
run_time("analyzer type does not support writing to a contents file");
bro_logger->Error("analyzer type does not support writing to a contents file");
return 0;
}

View file

@ -245,11 +245,8 @@ public:
{ conn->Event(f, this, v1, v2); }
void ConnectionEvent(EventHandlerPtr f, val_list* vl)
{ conn->ConnectionEvent(f, this, vl); }
void Weird(const char* name) { conn->Weird(name); }
void Weird(const char* name, const char* addl)
void Weird(const char* name, const char* addl = "")
{ conn->Weird(name, addl); }
void Weird(const char* name, int addl_len, const char* addl)
{ conn->Weird(name, addl_len, addl); };
// Factory function to instantiate new analyzers.
static Analyzer* InstantiateAnalyzer(AnalyzerTag::Tag tag, Connection* c);

View file

@ -159,7 +159,7 @@ int AnonymizeIPAddr_A50::PreservePrefix(ipaddr32_t input, int num_bits)
if ( ! before_anonymization )
{
run_time("prefix perservation specified after anonymization begun");
bro_logger->Error("prefix perservation specified after anonymization begun");
return 0;
}
@ -206,7 +206,7 @@ AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::new_node_block()
int block_size = 1024;
Node* block = new Node[block_size];
if ( ! block )
internal_error("out of memory!");
bro_logger->InternalError("out of memory!");
blocks.push_back(block);
@ -258,7 +258,7 @@ ipaddr32_t AnonymizeIPAddr_A50::make_output(ipaddr32_t old_output, int swivel) c
AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::make_peer(ipaddr32_t a, Node* n)
{
if ( a == 0 || a == 0xFFFFFFFFU )
internal_error("0.0.0.0 and 255.255.255.255 should never get into the tree");
bro_logger->InternalError("0.0.0.0 and 255.255.255.255 should never get into the tree");
// Become a peer.
// Algorithm: create two nodes, the two peers. Leave orig node as
@ -341,7 +341,7 @@ AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::find_node(ipaddr32_t a)
}
}
internal_error("out of memory!");
bro_logger->InternalError("out of memory!");
return 0;
}
@ -389,14 +389,14 @@ ipaddr32_t anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_class_t cl)
new_ip = ip;
else if ( ! ip_anonymizer[method] )
internal_error("IP anonymizer not initialized");
bro_logger->InternalError("IP anonymizer not initialized");
else
new_ip = ip_anonymizer[method]->Anonymize(ip);
}
else
internal_error("invalid IP anonymization method");
bro_logger->InternalError("invalid IP anonymization method");
#ifdef LOG_ANONYMIZATION_MAPPING
log_anonymization_mapping(ip, new_ip);

View file

@ -18,6 +18,7 @@
#include <map>
using namespace std;
#include "Logger.h"
#include "net_util.h"
// TODO: Anon.h may not be the right place to put these functions ...
@ -52,7 +53,7 @@ public:
// Keep the specified prefix unchanged.
virtual int PreservePrefix(ipaddr32_t /* input */, int /* num_bits */)
{
internal_error("prefix preserving is not supported for the anonymizer");
bro_logger->InternalError("prefix preserving is not supported for the anonymizer");
return 0;
}

View file

@ -46,7 +46,7 @@ int Base64Decoder::Decode(int len, const char* data, int* pblen, char** pbuf)
char* buf;
if ( ! pbuf )
internal_error("nil pointer to decoding result buffer");
bro_logger->InternalError("nil pointer to decoding result buffer");
if ( *pbuf )
{

View file

@ -46,7 +46,7 @@ public:
if ( analyzer )
analyzer->Weird("base64_illegal_encoding", msg);
else
run_time(msg);
bro_logger->Error(msg);
}
protected:

View file

@ -11,6 +11,7 @@
#include "BroString.h"
#include "Var.h"
#include "Logger.h"
#ifdef DEBUG
#define DEBUG_STR(msg) DBG_LOG(DBG_STRING, msg)
@ -175,9 +176,9 @@ const char* BroString::CheckString() const
// Either an embedded NUL, or no final NUL.
char* exp_s = Render();
if ( b[n-1] != '\0' )
run_time("string without NUL terminator: \"%s\"", exp_s);
bro_logger->Error("string without NUL terminator: \"%s\"", exp_s);
else
run_time("string with embedded NUL: \"%s\"", exp_s);
bro_logger->Error("string with embedded NUL: \"%s\"", exp_s);
delete [] exp_s;
return "<string-with-NUL>";

View file

@ -195,7 +195,7 @@ bool ChunkedIOFd::WriteChunk(Chunk* chunk, bool partial)
assert(chunk->len <= BUFFER_SIZE - sizeof(uint32) );
if ( chunk->len == 0 )
internal_error( "attempt to write 0 bytes chunk");
bro_logger->InternalError( "attempt to write 0 bytes chunk");
if ( partial )
chunk->len |= FLAG_PARTIAL;
@ -285,7 +285,7 @@ bool ChunkedIOFd::FlushWriteBuffer()
}
if ( written == 0 )
internal_error("written==0");
bro_logger->InternalError("written==0");
// Short write.
write_pos += written;
@ -906,7 +906,7 @@ bool ChunkedIOSSL::WriteData(char* p, uint32 len, bool* error)
return false;
}
internal_error("can't be reached");
bro_logger->InternalError("can't be reached");
return false;
}
@ -1026,7 +1026,7 @@ bool ChunkedIOSSL::ReadData(char* p, uint32 len, bool* error)
}
// Can't be reached.
internal_error("can't be reached");
bro_logger->InternalError("can't be reached");
return false;
}

View file

@ -6,6 +6,7 @@
#include "CompHash.h"
#include "Val.h"
#include "Logger.h"
CompositeHash::CompositeHash(TypeList* composite_type)
{
@ -191,7 +192,7 @@ char* CompositeHash::SingleValHash(int type_check, char* kp0,
}
else
{
internal_error("bad index type in CompositeHash::SingleValHash");
bro_logger->InternalError("bad index type in CompositeHash::SingleValHash");
return 0;
}
}
@ -314,7 +315,7 @@ HashKey* CompositeHash::ComputeSingletonHash(const Val* v, int type_check) const
if ( v->Type()->Tag() == TYPE_FUNC )
return new HashKey(v);
internal_error("bad index type in CompositeHash::ComputeSingletonHash");
bro_logger->InternalError("bad index type in CompositeHash::ComputeSingletonHash");
return 0;
case TYPE_INTERNAL_STRING:
@ -324,7 +325,7 @@ HashKey* CompositeHash::ComputeSingletonHash(const Val* v, int type_check) const
return 0;
default:
internal_error("bad internal type in CompositeHash::ComputeSingletonHash");
bro_logger->InternalError("bad internal type in CompositeHash::ComputeSingletonHash");
return 0;
}
}
@ -399,7 +400,7 @@ int CompositeHash::SingleTypeKeySize(BroType* bt, const Val* v,
}
else
{
internal_error("bad index type in CompositeHash::CompositeHash");
bro_logger->InternalError("bad index type in CompositeHash::CompositeHash");
return 0;
}
}
@ -522,7 +523,7 @@ ListVal* CompositeHash::RecoverVals(const HashKey* k) const
}
if ( kp != k_end )
internal_error("under-ran key in CompositeHash::DescribeKey %ld", k_end - kp);
bro_logger->InternalError("under-ran key in CompositeHash::DescribeKey %ld", k_end - kp);
return l;
}
@ -533,7 +534,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey* k, const char* kp0,
{
// k->Size() == 0 for a single empty string.
if ( kp0 >= k_end && k->Size() > 0 )
internal_error("over-ran key in CompositeHash::RecoverVals");
bro_logger->InternalError("over-ran key in CompositeHash::RecoverVals");
TypeTag tag = t->Tag();
InternalTypeTag it = t->InternalType();
@ -580,7 +581,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey* k, const char* kp0,
break;
default:
internal_error("bad internal unsigned int in CompositeHash::RecoverOneVal()");
bro_logger->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()");
pval = 0;
break;
}
@ -619,7 +620,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey* k, const char* kp0,
break;
default:
internal_error("bad internal address in CompositeHash::RecoverOneVal()");
bro_logger->InternalError("bad internal address in CompositeHash::RecoverOneVal()");
pval = 0;
break;
}
@ -648,21 +649,21 @@ const char* CompositeHash::RecoverOneVal(const HashKey* k, const char* kp0,
Val* v = *kp;
if ( ! v || ! v->Type() )
internal_error("bad aggregate Val in CompositeHash::RecoverOneVal()");
bro_logger->InternalError("bad aggregate Val in CompositeHash::RecoverOneVal()");
if ( t->Tag() != TYPE_FUNC &&
// ### Maybe fix later, but may be fundamentally
// un-checkable --US
! same_type(v->Type(), t) )
{
internal_error("inconsistent aggregate Val in CompositeHash::RecoverOneVal()");
bro_logger->InternalError("inconsistent aggregate Val in CompositeHash::RecoverOneVal()");
}
// ### A crude approximation for now.
if ( t->Tag() == TYPE_FUNC &&
v->Type()->Tag() != TYPE_FUNC )
{
internal_error("inconsistent aggregate Val in CompositeHash::RecoverOneVal()");
bro_logger->InternalError("inconsistent aggregate Val in CompositeHash::RecoverOneVal()");
}
pval = v->Ref();
@ -687,7 +688,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey* k, const char* kp0,
rt->FieldType(i), v, optional);
if ( ! (v || optional) )
{
internal_error("didn't recover expected number of fields from HashKey");
bro_logger->InternalError("didn't recover expected number of fields from HashKey");
pval = 0;
break;
}
@ -707,7 +708,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey* k, const char* kp0,
}
else
{
internal_error("bad index type in CompositeHash::DescribeKey");
bro_logger->InternalError("bad index type in CompositeHash::DescribeKey");
}
}
break;

View file

@ -34,7 +34,7 @@ protected:
// Recovers just one Val of possibly many; called from RecoverVals.
// Upon return, pval will point to the recovered Val of type t.
// Returns and updated kp for the next Val. Calls internal_error()
// Returns and updated kp for the next Val. Calls bro_logger->InternalError()
// upon errors, so there is no return value for invalid input.
const char* RecoverOneVal(const HashKey* k,
const char* kp, const char* const k_end,

View file

@ -54,7 +54,7 @@ void ConnectionTimer::Init(Connection* arg_conn, timer_func arg_timer,
ConnectionTimer::~ConnectionTimer()
{
if ( conn->RefCnt() < 1 )
internal_error("reference count inconsistency in ~ConnectionTimer");
bro_logger->InternalError("reference count inconsistency in ~ConnectionTimer");
conn->RemoveTimer(this);
Unref(conn);
@ -72,7 +72,7 @@ void ConnectionTimer::Dispatch(double t, int is_expire)
(conn->*timer)(t);
if ( conn->RefCnt() < 1 )
internal_error("reference count inconsistency in ConnectionTimer::Dispatch");
bro_logger->InternalError("reference count inconsistency in ConnectionTimer::Dispatch");
}
IMPLEMENT_SERIAL(ConnectionTimer, SER_CONNECTION_TIMER);
@ -94,7 +94,7 @@ bool ConnectionTimer::DoSerialize(SerialInfo* info) const
else if ( timer == timer_func(&Connection::RemoveConnectionTimer) )
type = 4;
else
internal_error("unknown function in ConnectionTimer::DoSerialize()");
bro_logger->InternalError("unknown function in ConnectionTimer::DoSerialize()");
return conn->Serialize(info) && SERIALIZE(type) && SERIALIZE(do_expire);
}
@ -197,7 +197,7 @@ Connection::Connection(NetSessions* s, HashKey* k, double t, const ConnID* id)
Connection::~Connection()
{
if ( ! finished )
internal_error("Done() not called before destruction of Connection");
bro_logger->InternalError("Done() not called before destruction of Connection");
CancelTimers();
@ -636,54 +636,10 @@ void Connection::ConnectionEvent(EventHandlerPtr f, Analyzer* a, val_list* vl)
a ? a->GetID() : 0, GetTimerMgr(), this);
}
void Connection::Weird(const char* name)
{
weird = 1;
if ( conn_weird )
Event(conn_weird, 0, name);
else
fprintf(stderr, "%.06f weird: %s\n", network_time, name);
}
void Connection::Weird(const char* name, const char* addl)
{
weird = 1;
if ( conn_weird_addl )
{
val_list* vl = new val_list(3);
vl->append(new StringVal(name));
vl->append(BuildConnVal());
vl->append(new StringVal(addl));
ConnectionEvent(conn_weird_addl, 0, vl);
}
else
fprintf(stderr, "%.06f weird: %s (%s)\n", network_time, name, addl);
}
void Connection::Weird(const char* name, int addl_len, const char* addl)
{
weird = 1;
if ( conn_weird_addl )
{
val_list* vl = new val_list(3);
vl->append(new StringVal(name));
vl->append(BuildConnVal());
vl->append(new StringVal(addl_len, addl));
ConnectionEvent(conn_weird_addl, 0, vl);
}
else
{
fprintf(stderr, "%.06f weird: %s (", network_time, name);
for ( int i = 0; i < addl_len; ++i )
fputc(addl[i], stderr);
fprintf(stderr, ")\n");
}
bro_logger->Weird(this, name, addl ? addl : "");
}
void Connection::AddTimer(timer_func timer, double t, int do_expire,
@ -794,7 +750,7 @@ void Connection::Describe(ODesc* d) const
break;
case TRANSPORT_UNKNOWN:
internal_error("unknown transport in Connction::Describe()");
bro_logger->InternalError("unknown transport in Connction::Describe()");
break;
}

View file

@ -199,9 +199,7 @@ public:
void ConnectionEvent(EventHandlerPtr f, Analyzer* analyzer,
val_list* vl);
void Weird(const char* name);
void Weird(const char* name, const char* addl);
void Weird(const char* name, int addl_len, const char* addl);
void Weird(const char* name, const char* addl = "");
bool DidWeird() const { return weird != 0; }
// Cancel all associated timers.

View file

@ -663,7 +663,7 @@ const IP_Hdr* ConnCompressor::PendingConnToPacket(const PendingConn* c)
// only an IPv4 address.
#ifdef BROv6
if ( ! is_v4_addr(c->key.ip1) || ! is_v4_addr(c->key.ip2) )
internal_error("IPv6 snuck into connection compressor");
bro_logger->InternalError("IPv6 snuck into connection compressor");
#endif
*(uint32*) &ip->ip_src =
to_v4_addr(c->ip1_is_src ? c->key.ip1 : c->key.ip2);
@ -929,6 +929,14 @@ void ConnCompressor::Event(const PendingConn* pending, double t,
conn_val->SetOrigin(0);
}
if ( event == conn_weird )
{
// Special case to go through the logger.
const char* msg = arg->AsString()->CheckString();
bro_logger->Weird(conn_val->Ref(), msg);
return;
}
val_list* vl = new val_list;
if ( arg )
vl->append(arg);

View file

@ -165,11 +165,10 @@ private:
void Weird(const PendingConn* pending, double t, const char* msg)
{
if ( conn_weird )
// This will actually go through the Logger; Event() takes care of
// that.
Event(pending, t, conn_weird, TCP_ENDPOINT_INACTIVE, 0,
TCP_ENDPOINT_INACTIVE, new StringVal(msg));
else
fprintf(stderr, "%.06f weird: %s\n", t, msg);
}
static const int BLOCK_SIZE = 16 * 1024;

View file

@ -103,7 +103,7 @@ void ContentLine_Analyzer::DeliverStream(int len, const u_char* data,
buf = tmp;
if ( ! buf )
internal_error("out of memory delivering endpoint line");
bro_logger->InternalError("out of memory delivering endpoint line");
}
DoDeliver(len, data);
@ -125,7 +125,7 @@ void ContentLine_Analyzer::EndpointEOF(bool is_orig)
void ContentLine_Analyzer::SetPlainDelivery(int64_t length)
{
if ( length < 0 )
internal_error("negative length for plain delivery");
bro_logger->InternalError("negative length for plain delivery");
plain_delivery_length = length;
}

View file

@ -60,7 +60,7 @@ UUID::UUID(const u_char d[16])
UUID::UUID(const binpac::bytestring& uuid)
{
if ( uuid.length() != 16 )
internal_error("UUID length error");
bro_logger->InternalError("UUID length error");
memcpy(data, uuid.begin(), 16);
s = uuid_to_string(data);
}
@ -82,7 +82,7 @@ UUID::UUID(const char* str)
}
if ( i != 16 )
internal_error("invalid UUID string: %s", str);
bro_logger->InternalError("invalid UUID string: %s", str);
}
typedef map<UUID, BifEnum::dce_rpc_if_id> uuid_map_t;

View file

@ -35,6 +35,7 @@
#include "Event.h"
#include "Net.h"
#include "Var.h"
#include "Logger.h"
extern "C" {
extern int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
@ -352,7 +353,7 @@ DNS_Mgr::DNS_Mgr(DNS_MgrMode arg_mode)
nb_dns = nb_dns_init(err);
if ( ! nb_dns )
warn(fmt("problem initializing NB-DNS: %s", err));
bro_logger->Warning(fmt("problem initializing NB-DNS: %s", err));
dns_mapping_valid = dns_mapping_unverified = dns_mapping_new_name =
dns_mapping_lost_name = dns_mapping_name_changed =
@ -439,7 +440,7 @@ TableVal* DNS_Mgr::LookupHost(const char* name)
return d->Addrs()->ConvertToSet();
else
{
warn("no such host:", name);
bro_logger->Warning("no such host:", name);
return empty_addr_set();
}
}
@ -452,7 +453,7 @@ TableVal* DNS_Mgr::LookupHost(const char* name)
return empty_addr_set();
case DNS_FORCE:
internal_error("can't find DNS entry for %s in cache", name);
bro_logger->InternalError("can't find DNS entry for %s in cache", name);
return 0;
case DNS_DEFAULT:
@ -461,7 +462,7 @@ TableVal* DNS_Mgr::LookupHost(const char* name)
return LookupHost(name);
default:
internal_error("bad mode in DNS_Mgr::LookupHost");
bro_logger->InternalError("bad mode in DNS_Mgr::LookupHost");
return 0;
}
}
@ -482,7 +483,7 @@ Val* DNS_Mgr::LookupAddr(uint32 addr)
return d->Host();
else
{
warn("can't resolve IP address:", dotted_addr(addr));
bro_logger->Warning("can't resolve IP address:", dotted_addr(addr));
return new StringVal(dotted_addr(addr));
}
}
@ -495,7 +496,7 @@ Val* DNS_Mgr::LookupAddr(uint32 addr)
return new StringVal("<none>");
case DNS_FORCE:
internal_error("can't find DNS entry for %s in cache",
bro_logger->InternalError("can't find DNS entry for %s in cache",
dotted_addr(addr));
return 0;
@ -505,7 +506,7 @@ Val* DNS_Mgr::LookupAddr(uint32 addr)
return LookupAddr(addr);
default:
internal_error("bad mode in DNS_Mgr::LookupHost");
bro_logger->InternalError("bad mode in DNS_Mgr::LookupHost");
return 0;
}
}
@ -566,7 +567,7 @@ void DNS_Mgr::Resolve()
struct nb_dns_result r;
status = nb_dns_activity(nb_dns, &r, err);
if ( status < 0 )
internal_error(
bro_logger->InternalError(
"NB-DNS error in DNS_Mgr::WaitForReplies (%s)",
err);
else if ( status > 0 )
@ -744,7 +745,7 @@ void DNS_Mgr::CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm)
ListVal* new_a = new_dm->Addrs();
if ( ! prev_a || ! new_a )
internal_error("confused in DNS_Mgr::CompareMappings");
bro_logger->InternalError("confused in DNS_Mgr::CompareMappings");
ListVal* prev_delta = AddrListDelta(prev_a, new_a);
ListVal* new_delta = AddrListDelta(new_a, prev_a);
@ -814,7 +815,7 @@ void DNS_Mgr::LoadCache(FILE* f)
}
if ( ! m->NoMapping() )
internal_error("DNS cache corrupted");
bro_logger->InternalError("DNS cache corrupted");
delete m;
fclose(f);
@ -934,7 +935,7 @@ void DNS_Mgr::IssueAsyncRequests()
if ( ! dr->MakeRequest(nb_dns) )
{
run_time("can't issue DNS request");
bro_logger->Error("can't issue DNS request");
req->Timeout();
continue;
}
@ -1047,7 +1048,7 @@ void DNS_Mgr::Process()
int status = nb_dns_activity(nb_dns, &r, err);
if ( status < 0 )
internal_error("NB-DNS error in DNS_Mgr::Process (%s)", err);
bro_logger->InternalError("NB-DNS error in DNS_Mgr::Process (%s)", err);
else if ( status > 0 )
{
@ -1071,7 +1072,7 @@ int DNS_Mgr::AnswerAvailable(int timeout)
{
int fd = nb_dns_fd(nb_dns);
if ( fd < 0 )
internal_error("nb_dns_fd() failed in DNS_Mgr::WaitForReplies");
bro_logger->InternalError("nb_dns_fd() failed in DNS_Mgr::WaitForReplies");
fd_set read_fds;
@ -1088,11 +1089,11 @@ int DNS_Mgr::AnswerAvailable(int timeout)
{
if ( errno == EINTR )
return -1;
internal_error("problem with DNS select");
bro_logger->InternalError("problem with DNS select");
}
if ( status > 1 )
internal_error("strange return from DNS select");
bro_logger->InternalError("strange return from DNS select");
return status;
}

View file

@ -262,7 +262,7 @@ bool DPM::BuildInitialAnalyzerTree(TransportProto proto, Connection* conn,
}
default:
internal_error("unknown protocol");
bro_logger->InternalError("unknown protocol");
}
if ( ! root )

View file

@ -204,7 +204,10 @@ bool DbgBreakpoint::Reset()
break;
}
internal_error("DbgBreakpoint::Reset function incomplete.");
bro_logger->InternalError("DbgBreakpoint::Reset function incomplete.");
// Cannot be reached.
return false;
}
bool DbgBreakpoint::SetCondition(const string& new_condition)
@ -292,7 +295,7 @@ BreakCode DbgBreakpoint::ShouldBreak(Stmt* s)
assert(false);
default:
internal_error("Invalid breakpoint type in DbgBreakpoint::ShouldBreak");
bro_logger->InternalError("Invalid breakpoint type in DbgBreakpoint::ShouldBreak");
}
// If we got here, that means that the breakpoint could hit,
@ -309,7 +312,7 @@ BreakCode DbgBreakpoint::ShouldBreak(Stmt* s)
BreakCode DbgBreakpoint::ShouldBreak(double t)
{
if ( kind != BP_TIME )
internal_error("Calling ShouldBreak(time) on a non-time breakpoint");
bro_logger->InternalError("Calling ShouldBreak(time) on a non-time breakpoint");
if ( t < at_time )
return bcNoHit;
@ -350,6 +353,6 @@ void DbgBreakpoint::PrintHitMsg()
assert(false);
default:
internal_error("Missed a case in DbgBreakpoint::PrintHitMsg\n");
bro_logger->InternalError("Missed a case in DbgBreakpoint::PrintHitMsg\n");
}
}

View file

@ -4,16 +4,17 @@
#include "Debug.h"
#include "DbgWatch.h"
#include "Logger.h"
// Support classes
DbgWatch::DbgWatch(BroObj* var_to_watch)
{
internal_error("DbgWatch unimplemented");
bro_logger->InternalError("DbgWatch unimplemented");
}
DbgWatch::DbgWatch(Expr* expr_to_watch)
{
internal_error("DbgWatch unimplemented");
bro_logger->InternalError("DbgWatch unimplemented");
}
DbgWatch::~DbgWatch()

View file

@ -54,7 +54,7 @@ DebuggerState::~DebuggerState()
bool StmtLocMapping::StartsAfter(const StmtLocMapping* m2)
{
if ( ! m2 )
internal_error("Assertion failed: %s", "m2 != 0");
bro_logger->InternalError("Assertion failed: %s", "m2 != 0");
return loc.first_line > m2->loc.first_line ||
(loc.first_line == m2->loc.first_line &&
@ -362,7 +362,7 @@ vector<ParseLocationRec> parse_location_string(const string& s)
{
Filemap* map = g_dbgfilemaps.Lookup(loc_filename);
if ( ! map )
internal_error("Policy file %s should have been loaded\n",
bro_logger->InternalError("Policy file %s should have been loaded\n",
loc_filename);
if ( plr.line > how_many_lines_in(loc_filename) )
@ -603,7 +603,7 @@ int dbg_execute_command(const char* cmd)
#endif
if ( int(cmd_code) >= num_debug_cmds() )
internal_error("Assertion failed: %s", "int(cmd_code) < num_debug_cmds()");
bro_logger->InternalError("Assertion failed: %s", "int(cmd_code) < num_debug_cmds()");
// Dispatch to the op-specific handler (with args).
int retcode = dbg_dispatch_cmd(cmd_code, arguments);
@ -612,7 +612,7 @@ int dbg_execute_command(const char* cmd)
const DebugCmdInfo* info = get_debug_cmd_info(cmd_code);
if ( ! info )
internal_error("Assertion failed: %s", "info");
bro_logger->InternalError("Assertion failed: %s", "info");
if ( ! info )
return -2; // ### yuck, why -2?
@ -766,7 +766,7 @@ int dbg_handle_debug_input()
const Stmt* stmt = curr_frame->GetNextStmt();
if ( ! stmt )
internal_error("Assertion failed: %s", "stmt != 0");
bro_logger->InternalError("Assertion failed: %s", "stmt != 0");
const Location loc = *stmt->GetLocationInfo();
@ -872,7 +872,7 @@ bool pre_execute_stmt(Stmt* stmt, Frame* f)
p = g_debugger_state.breakpoint_map.equal_range(stmt);
if ( p.first == p.second )
internal_error("Breakpoint count nonzero, but no matching breakpoints");
bro_logger->InternalError("Breakpoint count nonzero, but no matching breakpoints");
for ( BPMapType::iterator i = p.first; i != p.second; ++i )
{
@ -943,11 +943,11 @@ Val* dbg_eval_expr(const char* expr)
(g_frame_stack.size() - 1) - g_debugger_state.curr_frame_idx;
if ( ! (frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()) )
internal_error("Assertion failed: %s", "frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()");
bro_logger->InternalError("Assertion failed: %s", "frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()");
Frame* frame = g_frame_stack[frame_idx];
if ( ! (frame) )
internal_error("Assertion failed: %s", "frame");
bro_logger->InternalError("Assertion failed: %s", "frame");
const BroFunc* func = frame->GetFunction();
if ( func )

View file

@ -194,7 +194,7 @@ static int dbg_backtrace_internal(int start, int end)
if ( start < 0 || end < 0 ||
(unsigned) start >= g_frame_stack.size() ||
(unsigned) end >= g_frame_stack.size() )
internal_error("Invalid stack frame index in DbgBacktraceInternal\n");
bro_logger->InternalError("Invalid stack frame index in DbgBacktraceInternal\n");
if ( start < end )
{
@ -325,7 +325,7 @@ int dbg_cmd_frame(DebugCmd cmd, const vector<string>& args)
// for 'list', 'break', etc.
const Stmt* stmt = g_frame_stack[user_frame_number]->GetNextStmt();
if ( ! stmt )
internal_error("Assertion failed: %s", "stmt != 0");
bro_logger->InternalError("Assertion failed: %s", "stmt != 0");
const Location loc = *stmt->GetLocationInfo();
g_debugger_state.last_loc = loc;
@ -365,7 +365,7 @@ int dbg_cmd_break(DebugCmd cmd, const vector<string>& args)
Stmt* stmt = g_frame_stack[user_frame_number]->GetNextStmt();
if ( ! stmt )
internal_error("Assertion failed: %s", "stmt != 0");
bro_logger->InternalError("Assertion failed: %s", "stmt != 0");
DbgBreakpoint* bp = new DbgBreakpoint();
bp->SetID(g_debugger_state.NextBPID());
@ -530,7 +530,7 @@ int dbg_cmd_break_set_state(DebugCmd cmd, const vector<string>& args)
break;
default:
internal_error("Invalid command in DbgCmdBreakSetState\n");
bro_logger->InternalError("Invalid command in DbgCmdBreakSetState\n");
}
}

View file

@ -28,10 +28,7 @@ DebugLogger::DebugLogger(const char* filename)
file = fopen(filename, "w");
if ( ! file )
{
fprintf(stderr, "Can't open '%s' for debugging output.", filename);
exit(1);
}
bro_logger->FatalError("can't open '%s' for debugging output.", filename);
setvbuf(file, NULL, _IOLBF, 0);
}
@ -68,7 +65,7 @@ void DebugLogger::EnableStreams(const char* s)
if ( strcasecmp("verbose", tok) == 0 )
verbose = true;
else
internal_error("unknown debug stream %s\n", tok);
bro_logger->InternalError("unknown debug stream %s\n", tok);
}
tok = strtok(0, ",");

View file

@ -9,6 +9,7 @@
#include "Desc.h"
#include "File.h"
#include "Logger.h"
#define DEFAULT_SIZE 128
#define SLOP 10
@ -72,14 +73,14 @@ void ODesc::PushIndent()
void ODesc::PopIndent()
{
if ( --indent_level < 0 )
internal_error("ODesc::PopIndent underflow");
bro_logger->InternalError("ODesc::PopIndent underflow");
NL();
}
void ODesc::PopIndentNoNL()
{
if ( --indent_level < 0 )
internal_error("ODesc::PopIndent underflow");
bro_logger->InternalError("ODesc::PopIndent underflow");
}
void ODesc::Add(const char* s, int do_indent)
@ -288,7 +289,7 @@ void ODesc::AddBytesRaw(const void* bytes, unsigned int n)
if ( ! write_failed )
// Most likely it's a "disk full" so report
// subsequent failures only once.
run_time(fmt("error writing to %s: %s", f->Name(), strerror(errno)));
bro_logger->Error(fmt("error writing to %s: %s", f->Name(), strerror(errno)));
write_failed = true;
return;
@ -324,5 +325,5 @@ void ODesc::Grow(unsigned int n)
void ODesc::OutOfMemory()
{
internal_error("out of memory");
bro_logger->InternalError("out of memory");
}

View file

@ -9,6 +9,7 @@
#endif
#include "Dict.h"
#include "Logger.h"
// If the mean bucket length exceeds the following then Insert() will
// increase the size of the hash table.
@ -474,7 +475,7 @@ void Dictionary::StartChangeSize(int new_size)
return;
if ( tbl2 )
internal_error("Dictionary::StartChangeSize() tbl2 not NULL");
bro_logger->InternalError("Dictionary::StartChangeSize() tbl2 not NULL");
Init2(new_size);
@ -521,7 +522,7 @@ void Dictionary::FinishChangeSize()
{
// Cheap safety check.
if ( num_entries != 0 )
internal_error(
bro_logger->InternalError(
"Dictionary::FinishChangeSize: num_entries is %d\n",
num_entries);

View file

@ -93,7 +93,7 @@ void EventMgr::QueueEvent(Event* event)
void EventMgr::Dispatch()
{
if ( ! head )
internal_error("EventMgr underflow");
bro_logger->InternalError("EventMgr underflow");
Event* current = head;

View file

@ -74,6 +74,9 @@ public:
const EventHandlerPtr& operator=(const EventHandlerPtr& h)
{ handler = h.handler; return *this; }
bool operator==(const EventHandlerPtr& h) const
{ return handler == h.handler; }
EventHandler* Ptr() { return handler; }
operator bool() const { return handler && *handler; }

View file

@ -91,7 +91,7 @@ void EventRegistry::SetGroup(const char* name, const char* group)
{
EventHandler* eh = Lookup(name);
if ( ! eh )
internal_error("unknown event handler in SetGroup()");
bro_logger->InternalError("unknown event handler in SetGroup()");
eh->SetGroup(group);
}

View file

@ -300,7 +300,7 @@ Val* NameExpr::Eval(Frame* f) const
return v->Ref();
else
{
RunTime("value used but not set");
Error("value used but not set");
return 0;
}
}
@ -383,7 +383,7 @@ bool NameExpr::DoUnserialize(UnserialInfo* info)
if ( id )
::Ref(id);
else
run_time("unserialized unknown global name");
bro_logger->Warning("unserialized unknown global name");
delete [] name;
}
@ -626,7 +626,7 @@ Val* BinaryExpr::Eval(Frame* f) const
if ( v_op1->Size() != v_op2->Size() )
{
RunTime("vector operands are of different sizes");
Error("vector operands are of different sizes");
return 0;
}
@ -1040,7 +1040,7 @@ Val* IncrExpr::DoSingleEval(Frame* f, Val* v) const
if ( k < 0 &&
v->Type()->InternalType() == TYPE_INTERNAL_UNSIGNED )
RunTime("count underflow");
Error("count underflow");
}
BroType* ret_type = Type();
@ -1959,7 +1959,7 @@ Val* BoolExpr::Eval(Frame* f) const
if ( vec_v1->Size() != vec_v2->Size() )
{
RunTime("vector operands have different sizes");
Error("vector operands have different sizes");
return 0;
}
@ -2341,7 +2341,7 @@ Val* CondExpr::Eval(Frame* f) const
if ( cond->Size() != a->Size() || a->Size() != b->Size() )
{
RunTime("vectors in conditional expression have different sizes");
Error("vectors in conditional expression have different sizes");
return 0;
}
@ -2942,7 +2942,7 @@ Val* IndexExpr::Eval(Frame* f) const
{
if ( v_v1->Size() != v_v2->Size() )
{
RunTime("size mismatch, boolean index and vector");
Error("size mismatch, boolean index and vector");
return 0;
}
@ -2989,7 +2989,7 @@ Val* IndexExpr::Fold(Val* v1, Val* v2) const
if ( v )
return v->Ref();
RunTime("no such index");
Error("no such index");
return 0;
}
@ -4894,7 +4894,7 @@ Val* ListExpr::Eval(Frame* f) const
Val* ev = exprs[i]->Eval(f);
if ( ! ev )
{
RunTime("uninitialized list value");
Error("uninitialized list value");
return 0;
}
@ -5623,7 +5623,7 @@ int same_expr(const Expr* e1, const Expr* e2)
}
default:
internal_error("bad tag in same_expr()");
bro_logger->InternalError("bad tag in same_expr()");
}
return 0;
@ -5643,7 +5643,7 @@ static Expr* make_constant(BroType* t, double d)
case TYPE_INTERNAL_DOUBLE: v = new Val(double(d), t->Tag()); break;
default:
internal_error("bad type in make_constant()");
bro_logger->InternalError("bad type in make_constant()");
}
return new ConstExpr(v);

View file

@ -30,6 +30,7 @@
#include "Net.h"
#include "Serializer.h"
#include "Event.h"
#include "Logger.h"
// Timer which on dispatching rotates the file.
class RotateTimer : public Timer {
@ -93,7 +94,7 @@ static int maximize_num_fds()
#else
struct rlimit rl;
if ( getrlimit(RLIMIT_NOFILE, &rl) < 0 )
internal_error("maximize_num_fds(): getrlimit failed");
bro_logger->InternalError("maximize_num_fds(): getrlimit failed");
if ( rl.rlim_max == RLIM_INFINITY )
{
@ -109,7 +110,7 @@ static int maximize_num_fds()
rl.rlim_cur = rl.rlim_max;
if ( setrlimit(RLIMIT_NOFILE, &rl) < 0 )
internal_error("maximize_num_fds(): setrlimit failed");
bro_logger->InternalError("maximize_num_fds(): setrlimit failed");
return rl.rlim_cur / 2;
#endif
@ -150,7 +151,7 @@ BroFile::BroFile(const char* arg_name, const char* arg_access, BroType* arg_t)
t = arg_t ? arg_t : base_type(TYPE_STRING);
if ( ! Open() )
{
error(fmt("cannot open %s: %s", name, strerror(errno)));
bro_logger->Error(fmt("cannot open %s: %s", name, strerror(errno)));
is_open = 0;
okay_to_manage = 0;
}
@ -272,7 +273,7 @@ FILE* BroFile::File()
FILE* BroFile::BringIntoCache()
{
if ( f )
internal_error("BroFile non-nil non-open file");
bro_logger->InternalError("BroFile non-nil non-open file");
if ( num_files_in_cache >= max_files_in_cache )
PurgeCache();
@ -286,12 +287,12 @@ FILE* BroFile::BringIntoCache()
if ( ! f )
{
run_time("can't open %s", this);
bro_logger->Error("can't open %s", this);
f = fopen("/dev/null", "w");
if ( ! f )
internal_error("out of file descriptors");
bro_logger->InternalError("out of file descriptors");
okay_to_manage = 0;
return f;
@ -301,7 +302,7 @@ FILE* BroFile::BringIntoCache()
UpdateFileSize();
if ( fseek(f, position, SEEK_SET) < 0 )
run_time("reopen seek failed", this);
bro_logger->Error("reopen seek failed", this);
InsertAtBeginning();
@ -314,7 +315,7 @@ FILE* BroFile::Seek(long new_position)
return 0;
if ( fseek(f, new_position, SEEK_SET) < 0 )
run_time("seek failed", this);
bro_logger->Error("seek failed", this);
return f;
}
@ -325,7 +326,7 @@ void BroFile::SetBuf(bool arg_buffered)
return;
if ( setvbuf(f, NULL, arg_buffered ? _IOFBF : _IOLBF, 0) != 0 )
run_time("setvbuf failed", this);
bro_logger->Error("setvbuf failed", this);
buffered = arg_buffered;
}
@ -376,18 +377,18 @@ int BroFile::Close()
void BroFile::Suspend()
{
if ( ! is_in_cache )
internal_error("BroFile::Suspend() called for non-cached file");
bro_logger->InternalError("BroFile::Suspend() called for non-cached file");
if ( ! is_open )
internal_error("BroFile::Suspend() called for non-open file");
bro_logger->InternalError("BroFile::Suspend() called for non-open file");
Unlink();
if ( ! f )
internal_error("BroFile::Suspend() called for nil file");
bro_logger->InternalError("BroFile::Suspend() called for nil file");
if ( (position = ftell(f)) < 0 )
{
run_time("ftell failed", this);
bro_logger->Error("ftell failed", this);
position = 0;
}
@ -398,7 +399,7 @@ void BroFile::Suspend()
void BroFile::PurgeCache()
{
if ( ! tail )
internal_error("BroFile purge of empty cache");
bro_logger->InternalError("BroFile purge of empty cache");
tail->Suspend();
}
@ -418,13 +419,13 @@ void BroFile::Unlink()
Next()->SetPrev(prev);
if ( (head || tail) && ! (head && tail) )
internal_error("BroFile link list botch");
bro_logger->InternalError("BroFile link list botch");
is_in_cache = 0;
prev = next = 0;
if ( --num_files_in_cache < 0 )
internal_error("BroFile underflow of file cache");
bro_logger->InternalError("BroFile underflow of file cache");
}
}
@ -444,7 +445,7 @@ void BroFile::InsertAtBeginning()
}
if ( ++num_files_in_cache > max_files_in_cache )
internal_error("BroFile overflow of file cache");
bro_logger->InternalError("BroFile overflow of file cache");
is_in_cache = 1;
}
@ -455,7 +456,7 @@ void BroFile::MoveToBeginning()
return; // already at the beginning
if ( ! is_in_cache || ! prev )
internal_error("BroFile inconsistency in MoveToBeginning()");
bro_logger->InternalError("BroFile inconsistency in MoveToBeginning()");
Unlink();
InsertAtBeginning();
@ -642,7 +643,7 @@ void BroFile::InitEncrypt(const char* keyfile)
if ( ! key )
{
error(fmt("can't open key file %s: %s", keyfile, strerror(errno)));
bro_logger->Error(fmt("can't open key file %s: %s", keyfile, strerror(errno)));
Close();
return;
}
@ -650,7 +651,7 @@ void BroFile::InitEncrypt(const char* keyfile)
pub_key = PEM_read_PUBKEY(key, 0, 0, 0);
if ( ! pub_key )
{
error(fmt("can't read key from %s: %s", keyfile,
bro_logger->Error(fmt("can't read key from %s: %s", keyfile,
ERR_error_string(ERR_get_error(), 0)));
Close();
return;
@ -672,7 +673,7 @@ void BroFile::InitEncrypt(const char* keyfile)
if ( ! EVP_SealInit(cipher_ctx, cipher_type, &psecret,
(int*) &secret_len, iv, &pub_key, 1) )
{
error(fmt("can't init cipher context for %s: %s", keyfile,
bro_logger->Error(fmt("can't init cipher context for %s: %s", keyfile,
ERR_error_string(ERR_get_error(), 0)));
Close();
return;
@ -685,7 +686,7 @@ void BroFile::InitEncrypt(const char* keyfile)
fwrite(secret, ntohl(secret_len), 1, f) &&
fwrite(iv, iv_len, 1, f)) )
{
error(fmt("can't write header to log file %s: %s",
bro_logger->Error(fmt("can't write header to log file %s: %s",
name, strerror(errno)));
Close();
return;
@ -710,7 +711,7 @@ void BroFile::FinishEncrypt()
if ( outl && ! fwrite(cipher_buffer, outl, 1, f) )
{
run_time(fmt("write error for %s: %s",
bro_logger->Error(fmt("write error for %s: %s",
name, strerror(errno)));
return;
}
@ -742,7 +743,7 @@ int BroFile::Write(const char* data, int len)
if ( ! EVP_SealUpdate(cipher_ctx, cipher_buffer, &outl,
(unsigned char*)data, inl) )
{
run_time(fmt("encryption error for %s: %s",
bro_logger->Error(fmt("encryption error for %s: %s",
name,
ERR_error_string(ERR_get_error(), 0)));
Close();
@ -751,7 +752,7 @@ int BroFile::Write(const char* data, int len)
if ( outl && ! fwrite(cipher_buffer, outl, 1, f) )
{
run_time(fmt("write error for %s: %s",
bro_logger->Error(fmt("write error for %s: %s",
name, strerror(errno)));
Close();
return 0;
@ -799,7 +800,7 @@ void BroFile::UpdateFileSize()
struct stat s;
if ( fstat(fileno(f), &s) < 0 )
{
run_time(fmt("can't stat fd for %s: %s", name, strerror(errno)));
bro_logger->Error(fmt("can't stat fd for %s: %s", name, strerror(errno)));
current_size = 0;
return;
}

View file

@ -3,6 +3,7 @@
#include <algorithm>
#include "FileAnalyzer.h"
#include "Logger.h"
#ifdef HAVE_LIBMAGIC
magic_t File_Analyzer::magic = 0;
@ -75,11 +76,11 @@ void File_Analyzer::InitMagic(magic_t* magic, int flags)
*magic = magic_open(flags);
if ( ! *magic )
error(fmt("can't init libmagic: %s", magic_error(*magic)));
bro_logger->Error(fmt("can't init libmagic: %s", magic_error(*magic)));
else if ( magic_load(*magic, 0) < 0 )
{
error(fmt("can't load magic file: %s", magic_error(*magic)));
bro_logger->Error(fmt("can't load magic file: %s", magic_error(*magic)));
magic_close(*magic);
*magic = 0;
}

View file

@ -77,7 +77,7 @@ int FlowSocketSrc::ExtractNextPDU()
(struct sockaddr*) &from, &fromlen);
if ( pdu_len < 0 )
{
run_time("problem reading NetFlow data from socket");
bro_logger->Error("problem reading NetFlow data from socket");
data = 0;
next_timestamp = -1.0;
closed = 1;
@ -86,7 +86,7 @@ int FlowSocketSrc::ExtractNextPDU()
if ( fromlen != sizeof(from) )
{
run_time("malformed NetFlow PDU");
bro_logger->Error("malformed NetFlow PDU");
return 0;
}
@ -171,7 +171,7 @@ int FlowFileSrc::ExtractNextPDU()
if ( pdu_header.pdu_length > NF_MAX_PKT_SIZE )
{
run_time("NetFlow packet too long");
bro_logger->Error("NetFlow packet too long");
// Safely skip over the too-long PDU.
if ( lseek(selectable_fd, pdu_header.pdu_length, SEEK_CUR) < 0 )

View file

@ -24,7 +24,7 @@ void FragTimer::Dispatch(double t, int /* is_expire */)
if ( f )
f->Expire(t);
else
internal_error("fragment timer dispatched w/o reassembler");
bro_logger->InternalError("fragment timer dispatched w/o reassembler");
}
FragReassembler::FragReassembler(NetSessions* arg_s,
@ -209,7 +209,7 @@ void FragReassembler::BlockInserted(DataBlock* /* start_block */)
break;
if ( b->upper > n )
internal_error("bad fragment reassembly");
bro_logger->InternalError("bad fragment reassembly");
memcpy((void*) &pkt[b->seq], (const void*) b->block,
b->upper - b->seq);

View file

@ -48,6 +48,7 @@
#include "RemoteSerializer.h"
#include "Event.h"
#include "Traverse.h"
#include "Logger.h"
extern RETSIGTYPE sig_handler(int signo);
@ -333,7 +334,7 @@ Val* BroFunc::Call(val_list* args, Frame* parent) const
(flow != FLOW_RETURN /* we fell off the end */ ||
! result /* explicit return with no result */) &&
! f->HasDelayed() )
warn("non-void function returns without a value:", id->Name());
bro_logger->Warning("non-void function returns without a value:", id->Name());
if ( result && g_trace_state.DoTrace() )
{
@ -425,9 +426,9 @@ BuiltinFunc::BuiltinFunc(built_in_func arg_func, const char* arg_name,
id = lookup_ID(name, GLOBAL_MODULE_NAME, false);
if ( ! id )
internal_error("built-in function %s missing", name);
bro_logger->InternalError("built-in function %s missing", name);
if ( id->HasVal() )
internal_error("built-in function %s multiply defined", name);
bro_logger->InternalError("built-in function %s multiply defined", name);
id->SetVal(new Val(this));
}
@ -499,12 +500,12 @@ bool BuiltinFunc::DoUnserialize(UnserialInfo* info)
return UNSERIALIZE_STR(&name, 0);
}
void builtin_run_time(const char* msg, BroObj* arg)
void builtin_error(const char* msg, BroObj* arg)
{
if ( calling_expr )
calling_expr->RunTime(msg, arg);
calling_expr->Error(msg, arg);
else
run_time(msg, arg);
bro_logger->Error(msg, arg);
}
#include "bro.bif.func_h"

View file

@ -132,7 +132,7 @@ protected:
};
extern void builtin_run_time(const char* msg, BroObj* arg = 0);
extern void builtin_error(const char* msg, BroObj* arg = 0);
extern void init_builtin_funcs();
extern bool check_built_in_call(BuiltinFunc* f, CallExpr* call);

View file

@ -574,7 +574,7 @@ void HTTP_Message::SubmitData(int len, const char* buf)
{
if ( buf != (const char*) data_buffer->Bytes() + buffer_offset ||
buffer_offset + len > buffer_size )
internal_error("buffer misalignment");
bro_logger->InternalError("buffer misalignment");
buffer_offset += len;
if ( buffer_offset >= buffer_size )
@ -622,7 +622,7 @@ void HTTP_Message::SubmitEvent(int event_type, const char* detail)
break;
default:
internal_error("unrecognized HTTP message event");
bro_logger->InternalError("unrecognized HTTP message event");
}
MyHTTP_Analyzer()->HTTP_Event(category, detail);
@ -1095,7 +1095,7 @@ int HTTP_Analyzer::HTTP_RequestLine(const char* line, const char* end_of_line)
request_method = new StringVal(http_methods[i]);
if ( ! ParseRequest(rest, end_of_line) )
internal_error("HTTP ParseRequest failed");
bro_logger->InternalError("HTTP ParseRequest failed");
Conn()->Match(Rule::HTTP_REQUEST,
(const u_char*) unescaped_URI->AsString()->Bytes(),

View file

@ -448,7 +448,7 @@ ID* ID::Unserialize(UnserialInfo* info)
break;
default:
internal_error("unknown type for UnserialInfo::id_policy");
bro_logger->InternalError("unknown type for UnserialInfo::id_policy");
}
}
@ -552,7 +552,7 @@ bool ID::DoUnserialize(UnserialInfo* info)
}
if ( installed_tmp && ! global_scope()->Remove(name) )
internal_error("tmp id missing");
bro_logger->InternalError("tmp id missing");
return true;
}

View file

@ -1178,7 +1178,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig)
AddSupportAnalyzer(new ZIP_Analyzer(Conn(), true));
AddSupportAnalyzer(new ZIP_Analyzer(Conn(), false));
#else
run_time("IRC analyzer lacking libz support");
bro_logger->Error("IRC analyzer lacking libz support");
Remove();
#endif
}

View file

@ -73,7 +73,10 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig)
}
if ( line != end_of_line )
Weird("ident_request_addendum", length, orig_line);
{
BroString s((const u_char*)orig_line, length, true);
Weird("ident_request_addendum", s.CheckString());
}
val_list* vl = new val_list;
vl->append(BuildConnVal());
@ -233,14 +236,16 @@ const char* Ident_Analyzer::ParsePort(const char* line, const char* end_of_line,
void Ident_Analyzer::BadRequest(int length, const char* line)
{
Weird("bad_ident_request", length, line);
BroString s((const u_char*)line, length, true);
Weird("bad_ident_request", s.CheckString());
}
void Ident_Analyzer::BadReply(int length, const char* line)
{
if ( ! did_bad_reply )
{
Weird("bad_ident_reply", length, line);
BroString s((const u_char*)line, length, true);
Weird("bad_ident_reply", s.CheckString());
did_bad_reply = 1;
}
}

View file

@ -273,7 +273,7 @@ bool LogVal::Read(SerializationFormat* fmt)
}
default:
internal_error("unsupported type %s in LogVal::Write", type_name(type));
bro_logger->InternalError("unsupported type %s in LogVal::Write", type_name(type));
}
return false;
@ -374,7 +374,7 @@ bool LogVal::Write(SerializationFormat* fmt) const
}
default:
internal_error("unsupported type %s in LogVal::REad", type_name(type));
bro_logger->InternalError("unsupported type %s in LogVal::REad", type_name(type));
}
return false;
@ -452,7 +452,7 @@ bool LogMgr::CreateStream(EnumVal* id, RecordVal* sval)
if ( ! same_type(rtype, BifType::Record::Log::Stream, 0) )
{
run_time("sval argument not of right type");
bro_logger->Error("sval argument not of right type");
return false;
}
@ -468,7 +468,7 @@ bool LogMgr::CreateStream(EnumVal* id, RecordVal* sval)
if ( ! LogVal::IsCompatibleType(columns->FieldType(i)) )
{
run_time("type of field '%s' is not support for logging output",
bro_logger->Error("type of field '%s' is not support for logging output",
columns->FieldName(i));
return false;
@ -479,7 +479,7 @@ bool LogMgr::CreateStream(EnumVal* id, RecordVal* sval)
if ( ! log_attr_present )
{
run_time("logged record type does not have any &log attributes");
bro_logger->Error("logged record type does not have any &log attributes");
return false;
}
@ -493,7 +493,7 @@ bool LogMgr::CreateStream(EnumVal* id, RecordVal* sval)
if ( ! etype->IsEvent() )
{
run_time("stream event is a function, not an event");
bro_logger->Error("stream event is a function, not an event");
return false;
}
@ -501,13 +501,13 @@ bool LogMgr::CreateStream(EnumVal* id, RecordVal* sval)
if ( args->length() != 1 )
{
run_time("stream event must take a single argument");
bro_logger->Error("stream event must take a single argument");
return false;
}
if ( ! same_type((*args)[0], columns) )
{
run_time("stream event's argument type does not match column record type");
bro_logger->Error("stream event's argument type does not match column record type");
return new Val(0, TYPE_BOOL);
}
}
@ -627,7 +627,7 @@ bool LogMgr::TraverseRecord(Stream* stream, Filter* filter, RecordType* rt,
else
{
run_time("unsupported field type for log column");
bro_logger->Error("unsupported field type for log column");
return false;
}
}
@ -666,7 +666,7 @@ bool LogMgr::TraverseRecord(Stream* stream, Filter* filter, RecordType* rt,
if ( ! filter->fields )
{
run_time("out of memory in add_filter");
bro_logger->Error("out of memory in add_filter");
return false;
}
@ -685,7 +685,7 @@ bool LogMgr::AddFilter(EnumVal* id, RecordVal* fval)
if ( ! same_type(rtype, BifType::Record::Log::Filter, 0) )
{
run_time("filter argument not of right type");
bro_logger->Error("filter argument not of right type");
return false;
}
@ -835,7 +835,7 @@ bool LogMgr::Write(EnumVal* id, RecordVal* columns)
if ( ! columns )
{
run_time("incompatible log record type");
bro_logger->Error("incompatible log record type");
return false;
}
@ -877,7 +877,7 @@ bool LogMgr::Write(EnumVal* id, RecordVal* columns)
if ( ! v->Type()->Tag() == TYPE_STRING )
{
run_time("path_func did not return string");
bro_logger->Error("path_func did not return string");
Unref(v);
return false;
}
@ -1061,7 +1061,7 @@ LogVal* LogMgr::ValToLogVal(Val* val, BroType* ty)
}
default:
internal_error("unsupported type for log_write");
bro_logger->InternalError("unsupported type for log_write");
}
return lval;
@ -1126,7 +1126,7 @@ LogWriter* LogMgr::CreateWriter(EnumVal* id, EnumVal* writer, string path,
{
if ( ld->type == BifEnum::Log::WRITER_DEFAULT )
{
run_time("unknow writer when creating writer");
bro_logger->Error("unknow writer when creating writer");
return 0;
}
@ -1285,7 +1285,7 @@ bool LogMgr::Flush(EnumVal* id)
void LogMgr::Error(LogWriter* writer, const char* msg)
{
run_time(fmt("error with writer for %s: %s",
bro_logger->Error(fmt("error with writer for %s: %s",
writer->Path().c_str(), msg));
}

View file

@ -2,14 +2,14 @@
//
// See the file "COPYING" in the main distribution directory for copyright.
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <syslog.h>
#include "config.h"
#include "File.h"
#include "Logger.h"
#include "Event.h"
#include "NetVar.h"
#include "Net.h"
#include "Conn.h"
#ifdef SYSLOG_INT
extern "C" {
@ -19,55 +19,294 @@ int closelog();
}
#endif
Logger::Logger(const char* name, BroFile* arg_f)
Logger* bro_logger = 0;
Logger::Logger()
{
openlog(name, 0, LOG_LOCAL5);
f = arg_f;
enabled = 1;
errors = 0;
via_events = false;
openlog("bro", 0, LOG_LOCAL5);
}
Logger::~Logger()
{
closelog();
Unref(f);
}
void Logger::Log(const char* msg)
void Logger::Message(const char* fmt, ...)
{
int has_timestamp =
(fabs(atof(msg) - network_time) <= 30.0) ||
(msg[0] == 't' && msg[1] == '=' && isdigit(msg[2]));
va_list ap;
va_start(ap, fmt);
DoLog("", log_message, stdout, 0, 0, true, true, fmt, ap);
va_end(ap);
}
if ( enabled )
void Logger::Warning(const char* fmt, ...)
{
const char* sub_msg = msg;
if ( has_timestamp )
va_list ap;
va_start(ap, fmt);
DoLog("warning", log_warning, stdout, 0, 0, true, true, fmt, ap);
va_end(ap);
}
void Logger::Error(const char* fmt, ...)
{
// Don't include the timestamp in the logging,
// as it gets tacked on by syslog anyway.
sub_msg = strchr(sub_msg, ' ');
if ( sub_msg )
++sub_msg; // skip over ' '
++errors;
va_list ap;
va_start(ap, fmt);
DoLog("error", log_error, stdout, 0, 0, true, true, fmt, ap);
va_end(ap);
}
void Logger::FatalError(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
// Always log to stderr.
DoLog("fatal error", 0, stderr, 0, 0, true, false, fmt, ap);
va_end(ap);
set_processing_status("TERMINATED", "fatal_error");
exit(1);
}
void Logger::FatalErrorWithCore(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
// Always log to stderr.
DoLog("fatal error", 0, stderr, 0, 0, true, false, fmt, ap);
va_end(ap);
set_processing_status("TERMINATED", "fatal_error");
abort();
}
void Logger::InternalError(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
// Always log to stderr.
DoLog("internal error", 0, stderr, 0, 0, true, false, fmt, ap);
va_end(ap);
set_processing_status("TERMINATED", "internal_error");
abort();
}
void Logger::InternalWarning(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
DoLog("internal warning", log_warning, stdout, 0, 0, true, true, fmt, ap);
va_end(ap);
}
void Logger::Syslog(const char* fmt, ...)
{
if ( reading_traces )
return;
va_list ap;
va_start(ap, fmt);
vsyslog(LOG_NOTICE, fmt, ap);
va_end(ap);
}
void Logger::WeirdHelper(EventHandlerPtr event, Val* conn_val, const char* name, const char* addl, ...)
{
val_list* vl = new val_list(1);
if ( conn_val )
vl->append(conn_val);
if ( addl )
vl->append(new StringVal(addl));
va_list ap;
va_start(ap, addl);
DoLog("weird", event, stdout, 0, vl, false, false, name, ap);
va_end(ap);
delete vl;
}
void Logger::WeirdFlowHelper(addr_type orig, addr_type resp, const char* name, ...)
{
val_list* vl = new val_list(2);
vl->append(new AddrVal(orig));
vl->append(new AddrVal(resp));
va_list ap;
va_start(ap, name);
DoLog("weird", flow_weird, stdout, 0, vl, false, false, name, ap);
va_end(ap);
delete vl;
}
void Logger::Weird(const char* name)
{
WeirdHelper(net_weird, 0, name, 0);
}
void Logger::Weird(Connection* conn, const char* name, const char* addl)
{
WeirdHelper(conn_weird, conn->BuildConnVal(), name, addl);
}
void Logger::Weird(Val* conn_val, const char* name, const char* addl)
{
WeirdHelper(conn_weird, conn_val, name, addl);
}
void Logger::Weird(addr_type orig, addr_type resp, const char* name)
{
WeirdFlowHelper(orig, resp, name);
}
void Logger::DoLog(const char* prefix, EventHandlerPtr event, FILE* out, Connection* conn, val_list* addl, bool location, bool time, const char* fmt, va_list ap)
{
static char tmp[512];
int size = sizeof(tmp);
char* buffer = tmp;
char* alloced = 0;
string loc_str;
if ( location )
{
string loc_file = "";
int loc_line = 0;
if ( locations.size() )
{
ODesc d;
std::pair<const Location*, const Location*> locs = locations.back();
if ( locs.first )
{
if ( locs.first != &no_location )
locs.first->Describe(&d);
else
sub_msg = msg;
}
d.Add("<no location>");
syslog(LOG_NOTICE, "%s", sub_msg);
}
if ( f )
if ( locs.second )
{
if ( has_timestamp )
f->Write(fmt("%s\n", msg));
d.Add(" and ");
if ( locs.second != &no_location )
locs.second->Describe(&d);
else
f->Write(fmt("%.6f %s\n", network_time, msg));
d.Add("<no location>");
f->Flush();
}
}
void Logger::Describe(ODesc* d) const
loc_str = d.Description();
}
else if ( filename && *filename )
{
d->AddSP("logger");
f->Describe(d);
// Take from globals.
loc_str = filename;
char tmp[32];
snprintf(tmp, 32, "%d", line_number);
loc_str += string(", line ") + string(tmp);
}
}
while ( true )
{
va_list aq;
va_copy(aq, ap);
int n = vsnprintf(buffer, size, fmt, aq);
va_end(aq);
if ( n > -1 && n < size )
// We had enough space;
break;
// Enlarge buffer;
size *= 2;
buffer = alloced = (char *)realloc(alloced, size);
if ( ! buffer )
FatalError("out of memory in logger");
}
if ( event && via_events )
{
val_list* vl = new val_list;
if ( time )
vl->append(new Val(network_time, TYPE_TIME));
vl->append(new StringVal(buffer));
if ( location )
vl->append(new StringVal(loc_str.c_str()));
if ( conn )
vl->append(conn->BuildConnVal());
if ( addl )
{
loop_over_list(*addl, i)
vl->append((*addl)[i]);
}
if ( conn )
conn->ConnectionEvent(event, 0, vl);
else
mgr.QueueEvent(event, vl);
}
else
{
string s = "";
if ( network_time )
{
char tmp[32];
snprintf(tmp, 32, "%.6f", network_time);
s += string(tmp) + " ";
}
if ( prefix && *prefix )
{
if ( loc_str != "" )
s += string(prefix) + " in " + loc_str + ": ";
else
s += string(prefix) + ": ";
}
else
{
if ( loc_str != "" )
s += loc_str + ": ";
}
s += buffer;
s += "\n";
fprintf(out, s.c_str());
}
if ( alloced )
free(alloced);
}

View file

@ -3,29 +3,95 @@
#ifndef logger_h
#define logger_h
#include <stdarg.h>
#include <list>
#include <utility>
#include "util.h"
#include "Obj.h"
#include "net_util.h"
#include "EventHandler.h"
class BroFile;
class Func;
class Connection;
class Location;
class Logger : public BroObj {
class Logger {
public:
Logger(const char* name, BroFile* f = 0);
virtual ~Logger();
Logger();
~Logger();
void Log(const char* msg);
// Report an informational message, nothing that needs specific
// attention.
void Message(const char* fmt, ...);
void SetEnabled(int do_enabled) { enabled = do_enabled; }
// Report a warning that may indicate a problem.
void Warning(const char* fmt, ...);
void Describe(ODesc* d) const;
// Report a non-fatal error. Processing proceeds normally after the error
// has been reported.
void Error(const char* fmt, ...);
protected:
BroFile* f; // associated file
int enabled; // if true, syslog'ing is done, otherwise just file log
// Returns the number of errors reported so far.
int Errors() { return errors; }
// Report a fatal error. Bro will terminate after the message has been
// reported.
void FatalError(const char* fmt, ...);
// Report a fatal error. Bro will terminate after the message has been
// reported and always generate a core dump.
void FatalErrorWithCore(const char* fmt, ...);
// Report a traffic weirdness, i.e., an unexpected protocol situation
// that may lead to incorrectly processing a connnection.
void Weird(const char* name); // Raises net_weird().
void Weird(Connection* conn, const char* name, const char* addl = ""); // Raises conn_weird().
void Weird(Val* conn_val, const char* name, const char* addl = ""); // Raises conn_weird().
void Weird(addr_type orig, addr_type resp, const char* name); // Raises flow_weird().
// Syslog a message. This methods does nothing if we're running offline
// from a trace.
void Syslog(const char* fmt, ...);
// Report about a potential internal problem. Bro will continue normally.
void InternalWarning(const char* fmt, ...);
// Report an internal program error. Bro will terminate with a core dump
// after the message has been reported.
void InternalError(const char* fmt, ...);
// Toggle whether non-fatal messages should be reported through the
// scripting layer rather on standard output. Fatal errors are always
// reported via stderr.
void ReportViaEvents(bool arg_via_events) { via_events = arg_via_events; }
// Associates the given location with subsequent output. We create a
// stack of location so that the most recent is always the one that will
// be assumed to be the current one. The pointer must remain valid until
// the location is popped.
void PushLocation(const Location* location)
{ locations.push_back(std::pair<const Location*, const Location*>(location, 0)); }
void PushLocation(const Location* loc1, const Location* loc2)
{ locations.push_back(std::pair<const Location*, const Location*>(loc1, loc2)); }
// Removes the top-most location information from stack.
void PopLocation()
{ locations.pop_back(); }
private:
void DoLog(const char* prefix, EventHandlerPtr event, FILE* out, Connection* conn, val_list* addl, bool location, bool time, const char* fmt, va_list ap);
void WeirdHelper(EventHandlerPtr event, Val* conn_val, const char* name, const char* addl, ...);
void WeirdFlowHelper(addr_type orig, addr_type resp, const char* name, ...);
int errors;
bool via_events;
std::list<std::pair<const Location*, const Location*> > locations;
};
extern Logger* bro_logger;
extern Func* alarm_hook;
#endif

View file

@ -115,7 +115,7 @@ void Login_Analyzer::NewLine(bool orig, char* line)
}
if ( state != LOGIN_STATE_CONFUSED )
internal_error("bad state in Login_Analyzer::NewLine");
bro_logger->InternalError("bad state in Login_Analyzer::NewLine");
// When we're in "confused", we feed each user input line to
// login_confused_text, but also scan the text in the
@ -572,7 +572,7 @@ void Login_Analyzer::AddUserText(const char* line)
char* Login_Analyzer::PeekUserText() const
{
if ( num_user_text <= 0 )
internal_error("underflow in Login_Analyzer::PeekUserText()");
bro_logger->InternalError("underflow in Login_Analyzer::PeekUserText()");
return user_text[user_text_first];
}

View file

@ -5,6 +5,7 @@
#include "NetVar.h"
#include "MIME.h"
#include "Event.h"
#include "Logger.h"
// Here are a few things to do:
//
@ -268,7 +269,7 @@ void MIME_Entity::init()
MIME_Entity::~MIME_Entity()
{
if ( ! end_of_data )
internal_error("EndOfData must be called before delete a MIME_Entity");
bro_logger->InternalError("EndOfData must be called before delete a MIME_Entity");
delete current_header_line;
Unref(content_type_str);
@ -653,7 +654,7 @@ int MIME_Entity::CheckBoundaryDelimiter(int len, const char* data)
{
if ( ! multipart_boundary )
{
warn("boundary delimiter was not specified for a multipart message\n");
bro_logger->Warning("boundary delimiter was not specified for a multipart message\n");
DEBUG_MSG("headers of the MIME entity for debug:\n");
DebugPrintHeaders();
return NOT_MULTIPART_BOUNDARY;
@ -799,7 +800,7 @@ void MIME_Entity::DecodeBase64(int len, const char* data)
char* prbuf = rbuf;
int decoded = base64_decoder->Decode(len, data, &rlen, &prbuf);
if ( prbuf != rbuf )
internal_error("buffer pointer modified in base64 decoding");
bro_logger->InternalError("buffer pointer modified in base64 decoding");
DataOctets(rlen, rbuf);
len -= decoded; data += decoded;
}
@ -808,7 +809,7 @@ void MIME_Entity::DecodeBase64(int len, const char* data)
void MIME_Entity::StartDecodeBase64()
{
if ( base64_decoder )
internal_error("previous Base64 decoder not released!");
bro_logger->InternalError("previous Base64 decoder not released!");
base64_decoder = new Base64Decoder(message->GetAnalyzer());
}
@ -825,7 +826,7 @@ void MIME_Entity::FinishDecodeBase64()
if ( base64_decoder->Done(&rlen, &prbuf) )
{ // some remaining data
if ( prbuf != rbuf )
internal_error("buffer pointer modified in base64 decoding");
bro_logger->InternalError("buffer pointer modified in base64 decoding");
if ( rlen > 0 )
DataOctets(rlen, rbuf);
}
@ -839,7 +840,7 @@ int MIME_Entity::GetDataBuffer()
int ret = message->RequestBuffer(&data_buf_length, &data_buf_data);
if ( ! ret || data_buf_length == 0 || data_buf_data == 0 )
{
// internal_error("cannot get data buffer from MIME_Message", "");
// bro_logger->InternalError("cannot get data buffer from MIME_Message", "");
return 0;
}
@ -1092,7 +1093,7 @@ void MIME_Mail::SubmitAllHeaders(MIME_HeaderList& hlist)
void MIME_Mail::SubmitData(int len, const char* buf)
{
if ( buf != (char*) data_buffer->Bytes() + buffer_start )
internal_error("buffer misalignment");
bro_logger->InternalError("buffer misalignment");
if ( compute_content_hash )
{
@ -1180,7 +1181,7 @@ void MIME_Mail::SubmitEvent(int event_type, const char* detail)
break;
default:
internal_error("unrecognized MIME_Mail event");
bro_logger->InternalError("unrecognized MIME_Mail event");
}
if ( mime_event )

View file

@ -193,7 +193,7 @@ public:
virtual ~MIME_Message()
{
if ( ! finished )
internal_error("Done() must be called before destruction");
bro_logger->InternalError("Done() must be called before destruction");
}
virtual void Done() { finished = 1; }

View file

@ -38,7 +38,7 @@ void TelnetOption::RecvOption(unsigned int type)
{
TelnetOption* peer = endp->FindPeerOption(code);
if ( ! peer )
internal_error("option peer missing in TelnetOption::RecvOption");
bro_logger->InternalError("option peer missing in TelnetOption::RecvOption");
// WILL/WONT/DO/DONT are messages we've *received* from our peer.
switch ( type ) {
@ -83,7 +83,7 @@ void TelnetOption::RecvOption(unsigned int type)
break;
default:
internal_error("bad option type in TelnetOption::RecvOption");
bro_logger->InternalError("bad option type in TelnetOption::RecvOption");
}
}
@ -163,7 +163,7 @@ void TelnetEncryptOption::RecvSubOption(u_char* data, int len)
(TelnetEncryptOption*) endp->FindPeerOption(code);
if ( ! peer )
internal_error("option peer missing in TelnetEncryptOption::RecvSubOption");
bro_logger->InternalError("option peer missing in TelnetEncryptOption::RecvSubOption");
if ( peer->DidRequest() || peer->DoingEncryption() ||
peer->Endpoint()->AuthenticationHasBeenAccepted() )
@ -199,7 +199,7 @@ void TelnetAuthenticateOption::RecvSubOption(u_char* data, int len)
(TelnetAuthenticateOption*) endp->FindPeerOption(code);
if ( ! peer )
internal_error("option peer missing in TelnetAuthenticateOption::RecvSubOption");
bro_logger->InternalError("option peer missing in TelnetAuthenticateOption::RecvSubOption");
if ( ! peer->DidRequestAuthentication() )
InconsistentOption(0);

View file

@ -108,15 +108,6 @@ RETSIGTYPE watchdog(int /* signo */)
int frac_pst =
int((processing_start_time - int_pst) * 1e6);
char msg[512];
safe_snprintf(msg, sizeof(msg),
"**watchdog timer expired, t = %d.%06d, start = %d.%06d, dispatched = %d",
int_ct, frac_ct, int_pst, frac_pst,
current_dispatched);
bro_logger->Log(msg);
run_time("watchdog timer expired");
if ( current_hdr )
{
if ( ! pkt_dumper )
@ -128,7 +119,7 @@ RETSIGTYPE watchdog(int /* signo */)
pkt_dumper = new PktDumper("watchdog-pkt.pcap");
if ( pkt_dumper->IsError() )
{
fprintf(stderr, "watchdog: can't open watchdog-pkt.pcap for writing\n");
bro_logger->Error("watchdog: can't open watchdog-pkt.pcap for writing\n");
pkt_dumper = 0;
}
}
@ -140,8 +131,10 @@ RETSIGTYPE watchdog(int /* signo */)
net_get_final_stats();
net_finish(0);
abort();
exit(1);
bro_logger->FatalErrorWithCore(
"**watchdog timer expired, t = %d.%06d, start = %d.%06d, dispatched = %d",
int_ct, frac_ct, int_pst, frac_pst,
current_dispatched);
}
}
@ -168,11 +161,8 @@ void net_init(name_list& interfaces, name_list& readfiles,
PktFileSrc* ps = new PktFileSrc(readfiles[i], filter);
if ( ! ps->IsOpen() )
{
fprintf(stderr, "%s: problem with trace file %s - %s\n",
bro_logger->FatalError("%s: problem with trace file %s - %s\n",
prog, readfiles[i], ps->ErrorMsg());
exit(1);
}
else
{
pkt_srcs.append(ps);
@ -188,12 +178,9 @@ void net_init(name_list& interfaces, name_list& readfiles,
TYPE_FILTER_SECONDARY);
if ( ! ps->IsOpen() )
{
fprintf(stderr, "%s: problem with trace file %s - %s\n",
bro_logger->FatalError("%s: problem with trace file %s - %s\n",
prog, readfiles[i],
ps->ErrorMsg());
exit(1);
}
else
{
pkt_srcs.append(ps);
@ -209,11 +196,8 @@ void net_init(name_list& interfaces, name_list& readfiles,
FlowFileSrc* fs = new FlowFileSrc(flowfiles[i]);
if ( ! fs->IsOpen() )
{
fprintf(stderr, "%s: problem with netflow file %s - %s\n",
bro_logger->FatalError("%s: problem with netflow file %s - %s\n",
prog, flowfiles[i], fs->ErrorMsg());
exit(1);
}
else
{
io_sources.Register(fs);
@ -232,11 +216,8 @@ void net_init(name_list& interfaces, name_list& readfiles,
ps = new PktInterfaceSrc(interfaces[i], filter);
if ( ! ps->IsOpen() )
{
fprintf(stderr, "%s: problem with interface %s - %s\n",
bro_logger->FatalError("%s: problem with interface %s - %s\n",
prog, interfaces[i], ps->ErrorMsg());
exit(1);
}
else
{
pkt_srcs.append(ps);
@ -250,12 +231,9 @@ void net_init(name_list& interfaces, name_list& readfiles,
filter, TYPE_FILTER_SECONDARY);
if ( ! ps->IsOpen() )
{
fprintf(stderr, "%s: problem with interface %s - %s\n",
bro_logger->Error("%s: problem with interface %s - %s\n",
prog, interfaces[i],
ps->ErrorMsg());
exit(1);
}
else
{
pkt_srcs.append(ps);
@ -271,11 +249,8 @@ void net_init(name_list& interfaces, name_list& readfiles,
FlowSocketSrc* fs = new FlowSocketSrc(netflows[i]);
if ( ! fs->IsOpen() )
{
fprintf(stderr, "%s: problem with netflow socket %s - %s\n",
bro_logger->Error("%s: problem with netflow socket %s - %s\n",
prog, netflows[i], fs->ErrorMsg());
exit(1);
}
else
{
io_sources.Register(fs);
@ -297,15 +272,12 @@ void net_init(name_list& interfaces, name_list& readfiles,
// interfaces with different-lengthed media.
pkt_dumper = new PktDumper(writefile);
if ( pkt_dumper->IsError() )
{
fprintf(stderr, "%s: can't open write file \"%s\" - %s\n",
bro_logger->FatalError("%s: can't open write file \"%s\" - %s\n",
prog, writefile, pkt_dumper->ErrorMsg());
exit(1);
}
ID* id = global_scope()->Lookup("trace_output_file");
if ( ! id )
run_time("trace_output_file not defined in bro.init");
bro_logger->Error("trace_output_file not defined in bro.init");
else
id->SetVal(new StringVal(writefile));
}
@ -565,7 +537,7 @@ void net_get_final_stats()
{
struct PktSrc::Stats s;
ps->Statistics(&s);
fprintf(stderr, "%d packets received on interface %s, %d dropped\n",
bro_logger->Message("%d packets received on interface %s, %d dropped\n",
s.received, ps->Interface(), s.dropped);
}
}
@ -588,8 +560,6 @@ void net_finish(int drain_events)
delete pkt_dumper;
// fprintf(stderr, "uhash: %d/%d\n", hash_cnt_uhash, hash_cnt_all);
#ifdef DEBUG
extern int reassem_seen_bytes, reassem_copied_bytes;
// DEBUG_MSG("Reassembly (TCP and IP/Frag): %d bytes seen, %d bytes copied\n",
@ -641,7 +611,7 @@ static double suspend_start = 0;
void net_suspend_processing()
{
if ( _processing_suspended == 0 )
bro_logger->Log("processing suspended");
bro_logger->Message("processing suspended");
++_processing_suspended;
}
@ -650,7 +620,7 @@ void net_continue_processing()
{
if ( _processing_suspended == 1 )
{
bro_logger->Log("processing continued");
bro_logger->Message("processing continued");
loop_over_list(pkt_srcs, i)
pkt_srcs[i]->ContinueAfterSuspend();
}

View file

@ -87,7 +87,7 @@ void OSFingerprint::collide(uint32 id)
if (sig[id].ttl % 32 && sig[id].ttl != 255 && sig[id].ttl % 30)
{
problems=1;
warn(fmt("OS fingerprinting: [!] Unusual TTL (%d) for signature '%s %s' (line %d).",
bro_logger->Warning(fmt("OS fingerprinting: [!] Unusual TTL (%d) for signature '%s %s' (line %d).",
sig[id].ttl,sig[id].os,sig[id].desc,sig[id].line));
}
@ -96,7 +96,7 @@ void OSFingerprint::collide(uint32 id)
if (!strcmp(sig[i].os,sig[id].os) &&
!strcmp(sig[i].desc,sig[id].desc)) {
problems=1;
warn(fmt("OS fingerprinting: [!] Duplicate signature name: '%s %s' (line %d and %d).",
bro_logger->Warning(fmt("OS fingerprinting: [!] Duplicate signature name: '%s %s' (line %d and %d).",
sig[i].os,sig[i].desc,sig[i].line,sig[id].line));
}
@ -279,7 +279,7 @@ do_const:
if (sig[id].opt[j] ^ sig[i].opt[j]) goto reloop;
problems=1;
warn(fmt("OS fingerprinting: [!] Signature '%s %s' (line %d)\n"
bro_logger->Warning(fmt("OS fingerprinting: [!] Signature '%s %s' (line %d)\n"
" is already covered by '%s %s' (line %d).",
sig[id].os,sig[id].desc,sig[id].line,sig[i].os,sig[i].desc,
sig[i].line));

View file

@ -15,7 +15,7 @@
#include "util.h"
#include "Dict.h"
#include "Logger.h"
// Size limit for size wildcards.
#define PACKET_BIG 100
@ -105,19 +105,19 @@ protected:
void Error(const char* msg)
{
error(msg);
bro_logger->Error(msg);
err = true;
}
void Error(const char* msg, int n)
{
error(msg, n);
bro_logger->Error(msg, n);
err = true;
}
void Error(const char* msg, const char* s)
{
error(msg, s);
bro_logger->Error(msg, s);
err = true;
}

View file

@ -52,6 +52,32 @@ bool Location::DoUnserialize(UnserialInfo* info)
&& UNSERIALIZE(&last_column);
}
void Location::Describe(ODesc* d) const
{
if ( filename )
{
d->Add(filename);
if ( first_line == 0 )
return;
d->AddSP(",");
}
if ( last_line != first_line )
{
d->Add("lines ");
d->Add(first_line);
d->Add("-");
d->Add(last_line);
}
else
{
d->Add("line ");
d->Add(first_line);
}
}
bool Location::operator==(const Location& l) const
{
if ( filename == l.filename ||
@ -61,7 +87,7 @@ bool Location::operator==(const Location& l) const
return false;
}
int BroObj::suppress_runtime = 0;
int BroObj::suppress_errors = 0;
BroObj::~BroObj()
{
@ -70,23 +96,21 @@ BroObj::~BroObj()
void BroObj::Warn(const char* msg, const BroObj* obj2, int pinpoint_only) const
{
DoMsg("warning,", msg, obj2, pinpoint_only);
++nwarn;
ODesc d;
DoMsg(&d, msg, obj2, pinpoint_only);
bro_logger->Warning("%s", d.Description());
bro_logger->PopLocation();
}
void BroObj::Error(const char* msg, const BroObj* obj2, int pinpoint_only) const
{
DoMsg("error,", msg, obj2, pinpoint_only);
++nerr;
}
if ( suppress_errors )
return;
void BroObj::RunTime(const char* msg, const BroObj* obj2, int pinpoint_only) const
{
if ( ! suppress_runtime )
{
DoMsg("run-time error,", msg, obj2, pinpoint_only);
++nruntime;
}
ODesc d;
DoMsg(&d, msg, obj2, pinpoint_only);
bro_logger->Error("%s", d.Description());
bro_logger->PopLocation();
}
void BroObj::BadTag(const char* msg, const char* t1, const char* t2) const
@ -100,19 +124,23 @@ void BroObj::BadTag(const char* msg, const char* t1, const char* t2) const
else
snprintf(out, sizeof(out), "%s", msg);
DoMsg("bad tag in", out);
Fatal();
ODesc d;
DoMsg(&d, out);
bro_logger->FatalError("%s", d.Description());
}
void BroObj::Internal(const char* msg) const
{
DoMsg("internal error:", msg);
Fatal();
ODesc d;
DoMsg(&d, msg);
bro_logger->InternalError("%s", d.Description());
}
void BroObj::InternalWarning(const char* msg) const
{
DoMsg("internal warning:", msg);
ODesc d;
DoMsg(&d, msg);
bro_logger->InternalWarning("%s", d.Description());
}
void BroObj::AddLocation(ODesc* d) const
@ -123,28 +151,7 @@ void BroObj::AddLocation(ODesc* d) const
return;
}
if ( location->filename )
{
d->Add(location->filename);
if ( location->first_line == 0 )
return;
d->AddSP(",");
}
if ( location->last_line != location->first_line )
{
d->Add("lines ");
d->Add(location->first_line);
d->Add("-");
d->Add(location->last_line);
}
else
{
d->Add("line ");
d->Add(location->first_line);
}
location->Describe(d);
}
bool BroObj::SetLocationInfo(const Location* start, const Location* end)
@ -177,39 +184,24 @@ void BroObj::UpdateLocationEndInfo(const Location& end)
location->last_column = end.last_column;
}
void BroObj::DoMsg(const char s1[], const char s2[], const BroObj* obj2,
void BroObj::DoMsg(ODesc* d, const char s1[], const BroObj* obj2,
int pinpoint_only) const
{
ODesc d;
d.SetShort();
d->SetShort();
PinPoint(&d, obj2, pinpoint_only);
d.SP();
d.Add(s1);
d.SP();
d.Add(s2);
fprintf(stderr, "%s\n", d.Description());
d->Add(s1);
PinPoint(d, obj2, pinpoint_only);
const Location* loc2 = 0;
if ( obj2 && obj2->GetLocationInfo() != &no_location &&
*obj2->GetLocationInfo() != *GetLocationInfo() )
loc2 = obj2->GetLocationInfo();
bro_logger->PushLocation(GetLocationInfo(), loc2);
}
void BroObj::PinPoint(ODesc* d, const BroObj* obj2, int pinpoint_only) const
{
if ( network_time > 0.0 )
{
char time[256];
safe_snprintf(time, sizeof(time), "%.6f", network_time);
d->Add(time);
d->SP();
}
AddLocation(d);
if ( obj2 && obj2->GetLocationInfo() != &no_location &&
*obj2->GetLocationInfo() != *GetLocationInfo() )
{
d->Add(" and ");
obj2->AddLocation(d);
d->Add("\n ");
}
d->Add(" (");
Describe(d);
if ( obj2 && ! pinpoint_only )
@ -218,15 +210,7 @@ void BroObj::PinPoint(ODesc* d, const BroObj* obj2, int pinpoint_only) const
obj2->Describe(d);
}
d->Add("):");
}
void BroObj::Fatal() const
{
#ifdef DEBUG_BRO
internal_error("BroObj::Fatal()");
#endif
exit(1);
d->Add(")");
}
bool BroObj::DoSerialize(SerialInfo* info) const
@ -260,7 +244,7 @@ void print(const BroObj* obj)
void bad_ref(int type)
{
internal_error("bad reference count [%d]", type);
bro_logger->InternalError("bad reference count [%d]", type);
abort();
}

View file

@ -44,6 +44,8 @@ public:
delete [] filename;
}
void Describe(ODesc* d) const;
bool Serialize(SerialInfo* info) const;
static Location* Unserialize(UnserialInfo* info);
@ -120,8 +122,6 @@ public:
int pinpoint_only = 0) const;
void Error(const char* msg, const BroObj* obj2 = 0,
int pinpoint_only = 0) const;
void RunTime(const char* msg, const BroObj* obj2 = 0,
int pinpoint_only = 0) const;
// Report internal errors.
void BadTag(const char* msg, const char* t1 = 0,
@ -155,12 +155,12 @@ public:
int RefCnt() const { return ref_cnt; }
// Helper class to temporarily suppress run-time errors
// Helper class to temporarily suppress errors
// as long as there exist any instances.
class SuppressRunTimeErrors {
class SuppressErrors {
public:
SuppressRunTimeErrors() { ++BroObj::suppress_runtime; }
~SuppressRunTimeErrors() { --BroObj::suppress_runtime; }
SuppressErrors() { ++BroObj::suppress_errors; }
~SuppressErrors() { --BroObj::suppress_errors; }
};
bool in_ser_cache;
@ -173,13 +173,12 @@ protected:
Location* location; // all that matters in real estate
private:
friend class SuppressRunTimeErrors;
friend class SuppressErrors;
void DoMsg(const char s1[], const char s2[], const BroObj* obj2 = 0,
void DoMsg(ODesc* d, const char s1[], const BroObj* obj2 = 0,
int pinpoint_only = 0) const;
void PinPoint(ODesc* d, const BroObj* obj2 = 0,
int pinpoint_only = 0) const;
void Fatal() const;
friend inline void Ref(BroObj* o);
friend inline void Unref(BroObj* o);
@ -188,7 +187,7 @@ private:
// If non-zero, do not print runtime errors. Useful for
// speculative evaluation.
static int suppress_runtime;
static int suppress_errors;
};
// Prints obj to stderr, primarily for debugging.

View file

@ -153,7 +153,7 @@ void PIA_UDP::ActivateAnalyzer(AnalyzerTag::Tag tag, const Rule* rule)
void PIA_UDP::DeactivateAnalyzer(AnalyzerTag::Tag tag)
{
internal_error("PIA_UDP::Deact not implemented yet");
bro_logger->InternalError("PIA_UDP::Deact not implemented yet");
}
//// TCP PIA
@ -375,7 +375,7 @@ void PIA_TCP::ActivateAnalyzer(AnalyzerTag::Tag tag, const Rule* rule)
void PIA_TCP::DeactivateAnalyzer(AnalyzerTag::Tag tag)
{
internal_error("PIA_TCP::Deact not implemented yet");
bro_logger->InternalError("PIA_TCP::Deact not implemented yet");
}
void PIA_TCP::ReplayStreamBuffer(Analyzer* analyzer)

View file

@ -15,6 +15,7 @@
#include "POP3.h"
#include "Event.h"
#include "NVT.h"
#include "Logger.h"
#undef POP3_CMD_DEF
#define POP3_CMD_DEF(cmd) #cmd,
@ -199,7 +200,7 @@ void POP3_Analyzer::ProcessRequest(int length, const char* line)
break;
default:
internal_error("unexpected authorization state");
bro_logger->InternalError("unexpected authorization state");
}
delete decoded;
@ -555,7 +556,7 @@ void POP3_Analyzer::ProcessClientCmd()
break;
default:
internal_error("command not known");
bro_logger->InternalError("command not known");
}
}
@ -807,7 +808,7 @@ void POP3_Analyzer::BeginData()
void POP3_Analyzer::EndData()
{
if ( ! mail )
warn("unmatched end of data");
bro_logger->Warning("unmatched end of data");
else
{
mail->Done();

View file

@ -18,7 +18,7 @@ PacketDumper::PacketDumper(pcap_dumper_t* arg_pkt_dump)
pkt_dump = arg_pkt_dump;
if ( ! pkt_dump )
internal_error("PacketDumper: nil dump file");
bro_logger->InternalError("PacketDumper: nil dump file");
}
void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr,
@ -29,7 +29,7 @@ void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr,
struct pcap_pkthdr h = *hdr;
h.caplen = len;
if ( h.caplen > hdr->caplen )
internal_error("bad modified caplen");
bro_logger->InternalError("bad modified caplen");
pcap_dump((u_char*) pkt_dump, &h, pkt);
}

View file

@ -347,7 +347,7 @@ PacketSortElement* PacketSortGlobalPQ::RemoveMin(double timestamp)
PacketSortConnPQ* PacketSortGlobalPQ::FindConnPQ(PacketSortElement* e)
{
if ( ! e->is_tcp )
internal_error("cannot find a connection for an invalid id");
bro_logger->InternalError("cannot find a connection for an invalid id");
PacketSortConnPQ* pq = (PacketSortConnPQ*) conn_pq_table.Lookup(e->key);
if ( ! pq )

View file

@ -213,7 +213,7 @@ void PersistenceSerializer::GotStateAccess(StateAccess* s)
void PersistenceSerializer::GotTimer(Timer* s)
{
run_time("PersistenceSerializer::GotTimer not implemented");
bro_logger->Error("PersistenceSerializer::GotTimer not implemented");
}
void PersistenceSerializer::GotConnection(Connection* c)
@ -228,7 +228,7 @@ void PersistenceSerializer::GotID(ID* id, Val* /* val */)
void PersistenceSerializer::GotPacket(Packet* p)
{
run_time("PersistenceSerializer::GotPacket not implemented");
bro_logger->Error("PersistenceSerializer::GotPacket not implemented");
}
bool PersistenceSerializer::LogAccess(const StateAccess& s)
@ -286,7 +286,7 @@ bool PersistenceSerializer::SendState(SourceID peer, bool may_suspend)
status->conns = &persistent_conns;
status->peer = peer;
bro_logger->Log("Sending state...");
bro_logger->Message("Sending state...");
return RunSerialization(status);
}
@ -301,7 +301,7 @@ bool PersistenceSerializer::SendConfig(SourceID peer, bool may_suspend)
status->ids = global_scope()->GetIDs();
status->peer = peer;
bro_logger->Log("Sending config...");
bro_logger->Message("Sending config...");
return RunSerialization(status);
}
@ -319,8 +319,7 @@ bool PersistenceSerializer::RunSerialization(SerialStatus* status)
{
if ( running[i]->type == status->type )
{
// ### We don't report this anymore as it would go to stderr.
// Warning(fmt("Serialization of type %d already running.", status->type));
bro_logger->Warning("Serialization of type %d already running.", status->type);
return false;
}
}
@ -382,14 +381,14 @@ bool PersistenceSerializer::RunSerialization(SerialStatus* status)
}
else
internal_error("unknown suspend state");
bro_logger->InternalError("unknown suspend state");
}
else if ( cont->Resuming() )
cont->Resume();
else
internal_error("unknown continuation state");
bro_logger->InternalError("unknown continuation state");
if ( status->id_cookie )
{
@ -505,7 +504,7 @@ bool PersistenceSerializer::DoIDSerialization(SerialStatus* status, ID* id)
break;
default:
internal_error("unknown serialization type");
bro_logger->InternalError("unknown serialization type");
}
return success;
@ -536,7 +535,7 @@ bool PersistenceSerializer::DoConnSerialization(SerialStatus* status,
break;
default:
internal_error("unknown serialization type");
bro_logger->InternalError("unknown serialization type");
}
return success;
@ -561,7 +560,7 @@ bool PersistenceSerializer::DoAccessSerialization(SerialStatus* status,
break;
default:
internal_error("unknown serialization type");
bro_logger->InternalError("unknown serialization type");
}
return success;

View file

@ -400,7 +400,7 @@ void PktSrc::Statistics(Stats* s)
else if ( pcap_stats(pd, &pstat) < 0 )
{
run_time("problem getting packet filter statistics: %s",
bro_logger->Error("problem getting packet filter statistics: %s",
ErrorMsg());
s->received = s->dropped = s->link = 0;
}
@ -463,7 +463,7 @@ PktInterfaceSrc::PktInterfaceSrc(const char* arg_interface, const char* filter,
// ### This needs autoconf'ing.
#ifdef HAVE_PCAP_INT_H
fprintf(stderr, "pcap bufsize = %d\n", ((struct pcap *) pd)->bufsize);
bro_logger->Message("pcap bufsize = %d\n", ((struct pcap *) pd)->bufsize);
#endif
#ifdef HAVE_LINUX
@ -486,7 +486,7 @@ PktInterfaceSrc::PktInterfaceSrc(const char* arg_interface, const char* filter,
// Couldn't get header size.
return;
fprintf(stderr, "listening on %s\n", interface);
bro_logger->Message("listening on %s\n", interface);
}
else
closed = true;
@ -518,7 +518,7 @@ PktFileSrc::PktFileSrc(const char* arg_readfile, const char* filter,
selectable_fd = fileno(pcap_file(pd));
if ( selectable_fd < 0 )
internal_error("OS does not support selectable pcap fd");
bro_logger->InternalError("OS does not support selectable pcap fd");
}
else
closed = true;

View file

@ -16,6 +16,7 @@ using namespace std;
#include "Debug.h"
#include "util.h"
#include "PolicyFile.h"
#include "Logger.h"
struct PolicyFile {
PolicyFile () { filedata = 0; lmtime = 0; }
@ -32,7 +33,7 @@ static PolicyFileMap policy_files;
int how_many_lines_in(const char* policy_filename)
{
if ( ! policy_filename )
internal_error("NULL value passed to how_many_lines_in\n");
bro_logger->InternalError("NULL value passed to how_many_lines_in\n");
FILE* throwaway = fopen(policy_filename, "r");
if ( ! throwaway )

View file

@ -1,6 +1,7 @@
// $Id: PrefixTable.cc 1016 2005-01-31 21:23:50Z vern $
#include "PrefixTable.h"
#include "Logger.h"
// IPv4 version.
inline static prefix_t* make_prefix(const uint32 addr, int width)
@ -36,7 +37,7 @@ void* PrefixTable::Insert(const_addr_type addr, int width, void* data)
Deref_Prefix(prefix);
if ( ! node )
internal_error("Cannot create node in patricia tree");
bro_logger->InternalError("Cannot create node in patricia tree");
void* old = node->data;
@ -65,7 +66,7 @@ void* PrefixTable::Insert(const Val* value, void* data)
break;
default:
internal_error("Wrong index type for PrefixTable");
bro_logger->InternalError("Wrong index type for PrefixTable");
return 0;
}
}
@ -99,7 +100,7 @@ void* PrefixTable::Lookup(const Val* value, bool exact) const
break;
default:
internal_error("Wrong index type %d for PrefixTable",
bro_logger->InternalError("Wrong index type %d for PrefixTable",
value->Type()->Tag());
return 0;
}
@ -137,7 +138,7 @@ void* PrefixTable::Remove(const Val* value)
break;
default:
internal_error("Wrong index type for PrefixTable");
bro_logger->InternalError("Wrong index type for PrefixTable");
return 0;
}
}

View file

@ -8,6 +8,7 @@
#include <stdlib.h>
#include "PriorityQueue.h"
#include "Logger.h"
#include "util.h"
PriorityQueue::PriorityQueue(int initial_size)
@ -52,7 +53,7 @@ PQ_Element* PriorityQueue::Remove(PQ_Element* e)
PQ_Element* e2 = Remove();
if ( e != e2 )
internal_error("inconsistency in PriorityQueue::Remove");
bro_logger->InternalError("inconsistency in PriorityQueue::Remove");
return e2;
}

View file

@ -114,7 +114,7 @@ int Specific_RE_Matcher::Compile(int lazy)
RE_set_input(pattern_text);
if ( RE_parse() )
{
run_time("error compiling pattern /%s/", pattern_text);
bro_logger->Error("error compiling pattern /%s/", pattern_text);
return 0;
}
@ -134,7 +134,7 @@ int Specific_RE_Matcher::Compile(int lazy)
int Specific_RE_Matcher::CompileSet(const string_list& set, const int_list& idx)
{
if ( set.length() != idx.length() )
internal_error("compileset: lengths of sets differ");
bro_logger->InternalError("compileset: lengths of sets differ");
rem = this;
@ -145,7 +145,7 @@ int Specific_RE_Matcher::CompileSet(const string_list& set, const int_list& idx)
RE_set_input(set[i]);
if ( RE_parse() )
{
run_time("error compiling pattern /%s/", set[i]);
bro_logger->Error("error compiling pattern /%s/", set[i]);
return 0;
}

View file

@ -263,7 +263,7 @@ int RPC_Interpreter::DeliverRPC(const u_char* buf, int n, int rpclen,
}
else if ( n < 0 )
internal_error("RPC underflow");
bro_logger->InternalError("RPC underflow");
return 1;
}
@ -473,7 +473,7 @@ bool Contents_RPC::CheckResync(int& len, const u_char*& data, bool orig)
if ( resync_toskip != 0 )
// Should never happen.
internal_error("RPC resync: skipping over data failed");
bro_logger->InternalError("RPC resync: skipping over data failed");
// Now lets see whether data points to the beginning of a RPC
// frame. If the resync processs is successful, we should be
@ -623,9 +623,7 @@ void Contents_RPC::DeliverStream(int len, const u_char* data, bool orig)
marker_buf.Init(4,4);
if ( ! dummy_p )
{
internal_error("inconsistent RPC record marker extraction");
}
bro_logger->InternalError("inconsistent RPC record marker extraction");
last_frag = (marker & 0x80000000) != 0;
marker &= 0x7fffffff;

View file

@ -127,7 +127,7 @@ void Contents_Rsh_Analyzer::DoDeliver(int len, const u_char* data)
break;
default:
internal_error("bad state in Contents_Rsh_Analyzer::DoDeliver");
bro_logger->InternalError("bad state in Contents_Rsh_Analyzer::DoDeliver");
break;
}
}
@ -179,7 +179,7 @@ void Rsh_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
void Rsh_Analyzer::ClientUserName(const char* s)
{
if ( client_name )
internal_error("multiple rsh client names");
bro_logger->InternalError("multiple rsh client names");
client_name = new StringVal(s);
}
@ -187,7 +187,7 @@ void Rsh_Analyzer::ClientUserName(const char* s)
void Rsh_Analyzer::ServerUserName(const char* s)
{
if ( username )
internal_error("multiple rsh initial client names");
bro_logger->InternalError("multiple rsh initial client names");
username = new StringVal(s);
}

View file

@ -24,7 +24,7 @@ DataBlock::DataBlock(const u_char* data, int size, int arg_seq,
block = new u_char[size];
if ( ! block )
internal_error("out of memory");
bro_logger->InternalError("out of memory");
memcpy((void*) block, (const void*) data, size);

View file

@ -186,6 +186,7 @@
#include "File.h"
#include "Conn.h"
#include "LogMgr.h"
#include "Logger.h"
extern "C" {
#include "setsignal.h"
@ -393,7 +394,7 @@ static bool sendToIO(ChunkedIO* io, ChunkedIO::Chunk* c)
{
if ( ! io->Write(c) )
{
warn(fmt("can't send chunk: %s", io->Error()));
bro_logger->Warning(fmt("can't send chunk: %s", io->Error()));
return false;
}
@ -405,7 +406,7 @@ static bool sendToIO(ChunkedIO* io, char msg_type, RemoteSerializer::PeerID id,
{
if ( ! sendCMsg(io, msg_type, id) )
{
warn(fmt("can't send message of type %d: %s", msg_type, io->Error()));
bro_logger->Warning(fmt("can't send message of type %d: %s", msg_type, io->Error()));
return false;
}
@ -420,7 +421,7 @@ static bool sendToIO(ChunkedIO* io, char msg_type, RemoteSerializer::PeerID id,
{
if ( ! sendCMsg(io, msg_type, id) )
{
warn(fmt("can't send message of type %d: %s", msg_type, io->Error()));
bro_logger->Warning(fmt("can't send message of type %d: %s", msg_type, io->Error()));
return false;
}
@ -663,7 +664,7 @@ void RemoteSerializer::Fork()
setpriority(PRIO_PROCESS, 0, 5);
child.Run();
internal_error("cannot be reached");
bro_logger->InternalError("cannot be reached");
}
}
@ -674,7 +675,7 @@ RemoteSerializer::PeerID RemoteSerializer::Connect(addr_type ip, uint16 port,
return true;
if ( ! initialized )
internal_error("remote serializer not initialized");
bro_logger->InternalError("remote serializer not initialized");
#ifdef BROv6
if ( ! is_v4_addr(ip) )
@ -735,13 +736,13 @@ bool RemoteSerializer::RequestSync(PeerID id, bool auth)
Peer* peer = LookupPeer(id, true);
if ( ! peer )
{
run_time(fmt("unknown peer id %d for request sync", int(id)));
bro_logger->Error(fmt("unknown peer id %d for request sync", int(id)));
return false;
}
if ( peer->phase != Peer::HANDSHAKE )
{
run_time(fmt("can't request sync from peer; wrong phase %d",
bro_logger->Error(fmt("can't request sync from peer; wrong phase %d",
peer->phase));
return false;
}
@ -762,13 +763,13 @@ bool RemoteSerializer::RequestLogs(PeerID id)
Peer* peer = LookupPeer(id, true);
if ( ! peer )
{
run_time(fmt("unknown peer id %d for request logs", int(id)));
bro_logger->Error(fmt("unknown peer id %d for request logs", int(id)));
return false;
}
if ( peer->phase != Peer::HANDSHAKE )
{
run_time(fmt("can't request logs from peer; wrong phase %d",
bro_logger->Error(fmt("can't request logs from peer; wrong phase %d",
peer->phase));
return false;
}
@ -787,13 +788,13 @@ bool RemoteSerializer::RequestEvents(PeerID id, RE_Matcher* pattern)
Peer* peer = LookupPeer(id, true);
if ( ! peer )
{
run_time(fmt("unknown peer id %d for request sync", int(id)));
bro_logger->Error(fmt("unknown peer id %d for request sync", int(id)));
return false;
}
if ( peer->phase != Peer::HANDSHAKE )
{
run_time(fmt("can't request events from peer; wrong phase %d",
bro_logger->Error(fmt("can't request events from peer; wrong phase %d",
peer->phase));
return false;
}
@ -854,7 +855,7 @@ bool RemoteSerializer::CompleteHandshake(PeerID id)
if ( p->phase != Peer::HANDSHAKE )
{
run_time(fmt("can't complete handshake; wrong phase %d",
bro_logger->Error(fmt("can't complete handshake; wrong phase %d",
p->phase));
return false;
}
@ -1123,7 +1124,7 @@ bool RemoteSerializer::SendCaptureFilter(PeerID id, const char* filter)
if ( peer->phase != Peer::HANDSHAKE )
{
run_time(fmt("can't sent capture filter to peer; wrong phase %d", peer->phase));
bro_logger->Error(fmt("can't sent capture filter to peer; wrong phase %d", peer->phase));
return false;
}
@ -1200,7 +1201,7 @@ bool RemoteSerializer::SendCapabilities(Peer* peer)
{
if ( peer->phase != Peer::HANDSHAKE )
{
run_time(fmt("can't sent capabilties to peer; wrong phase %d",
bro_logger->Error(fmt("can't sent capabilties to peer; wrong phase %d",
peer->phase));
return false;
}
@ -1223,7 +1224,7 @@ bool RemoteSerializer::Listen(addr_type ip, uint16 port, bool expect_ssl)
return true;
if ( ! initialized )
internal_error("remote serializer not initialized");
bro_logger->InternalError("remote serializer not initialized");
#ifdef BROv6
if ( ! is_v4_addr(ip) )
@ -1545,10 +1546,11 @@ bool RemoteSerializer::Poll(bool may_block)
}
default:
internal_error("unknown msgstate");
bro_logger->InternalError("unknown msgstate");
}
internal_error("cannot be reached");
bro_logger->InternalError("cannot be reached");
return false;
}
bool RemoteSerializer::DoMessage()
@ -1662,7 +1664,7 @@ bool RemoteSerializer::DoMessage()
return true; // keep going
}
internal_error("cannot be reached");
bro_logger->InternalError("cannot be reached");
return false;
}
@ -1953,7 +1955,7 @@ bool RemoteSerializer::ProcessConnected()
ID* descr = global_scope()->Lookup("peer_description");
if ( ! descr )
internal_error("peer_description not defined");
bro_logger->InternalError("peer_description not defined");
SerialInfo info(this);
SendID(&info, current_peer, *descr);
@ -2136,7 +2138,7 @@ bool RemoteSerializer::HandshakeDone(Peer* peer)
else if ( peer->sync_requested & Peer::WE )
peer->send_state = false;
else
internal_error("illegal sync_requested value");
bro_logger->InternalError("illegal sync_requested value");
}
else
{
@ -2834,7 +2836,7 @@ void RemoteSerializer::GotStateAccess(StateAccess* s)
void RemoteSerializer::GotTimer(Timer* s)
{
run_time("RemoteSerializer::GotTimer not implemented");
bro_logger->Error("RemoteSerializer::GotTimer not implemented");
}
void RemoteSerializer::GotPacket(Packet* p)
@ -2938,7 +2940,7 @@ bool RemoteSerializer::SendCMsgToChild(char msg_type, Peer* peer)
{
if ( ! sendCMsg(io, msg_type, peer ? peer->id : PEER_NONE) )
{
warn(fmt("can't send message of type %d: %s",
bro_logger->Warning(fmt("can't send message of type %d: %s",
msg_type, io->Error()));
return false;
}
@ -3011,7 +3013,7 @@ void RemoteSerializer::FatalError(const char* msg)
{
msg = fmt("fatal error, shutting down communication: %s", msg);
Log(LogError, msg);
error(msg);
bro_logger->Error(msg);
closed = true;
kill(child_pid, SIGQUIT);
@ -3052,7 +3054,7 @@ void RemoteSerializer::InternalCommError(const char* msg)
#ifdef DEBUG_COMMUNICATION
DumpDebugData();
#else
internal_error("%s", msg);
bro_logger->InternalError("%s", msg);
#endif
}
@ -3073,7 +3075,7 @@ static ChunkedIO* openDump(const char* file)
if ( fd < 0 )
{
fprintf(stderr, "cannot open %s: %s\n", file, strerror(errno));
bro_logger->Error("cannot open %s: %s\n", file, strerror(errno));
return 0;
}
@ -3090,7 +3092,7 @@ void RemoteSerializer::ReadDumpAsMessageType(const char* file)
if ( ! io->Read(&chunk, true ) )
{
fprintf(stderr, "cannot read %s: %s\n", file, strerror(errno));
bro_logger->Error("cannot read %s: %s\n", file, strerror(errno));
return;
}
@ -3405,11 +3407,11 @@ bool SocketComm::ProcessParentMessage()
}
default:
internal_error("unknown msg type %d", parent_msgtype);
bro_logger->InternalError("unknown msg type %d", parent_msgtype);
return true;
}
internal_error("cannot be reached");
bro_logger->InternalError("cannot be reached");
}
case ARGS:
@ -3432,10 +3434,11 @@ bool SocketComm::ProcessParentMessage()
}
default:
internal_error("unknown msgstate");
bro_logger->InternalError("unknown msgstate");
}
internal_error("cannot be reached");
bro_logger->InternalError("cannot be reached");
return false;
}
bool SocketComm::DoParentMessage()
@ -3493,7 +3496,7 @@ bool SocketComm::DoParentMessage()
peers[j]->io->DumpDebugData(fmt("comm-dump.child.peer.%d", id), false);
}
#else
internal_error("DEBUG_DUMP support not compiled in");
bro_logger->InternalError("DEBUG_DUMP support not compiled in");
#endif
return true;
}
@ -3553,10 +3556,11 @@ bool SocketComm::DoParentMessage()
return ForwardChunkToPeer();
default:
internal_error("ProcessParentMessage: unexpected state");
bro_logger->InternalError("ProcessParentMessage: unexpected state");
}
internal_error("cannot be reached");
bro_logger->InternalError("cannot be reached");
return false;
}
bool SocketComm::ForwardChunkToPeer()
@ -3616,7 +3620,7 @@ bool SocketComm::ProcessListen()
bool SocketComm::ProcessParentCompress()
{
#ifndef HAVE_LIBZ
internal_error("supposed to enable compression but don't have zlib");
bro_logger->InternalError("supposed to enable compression but don't have zlib");
return false;
#else
@ -3736,10 +3740,11 @@ bool SocketComm::ProcessRemoteMessage(SocketComm::Peer* peer)
}
default:
internal_error("ProcessRemoteMessage: unexpected state");
bro_logger->InternalError("ProcessRemoteMessage: unexpected state");
}
return true;
assert(false); // Cannot be reached.
return false;
}
bool SocketComm::ForwardChunkToParent(Peer* peer, ChunkedIO::Chunk* c)

View file

@ -192,7 +192,7 @@ void Contents_Rlogin_Analyzer::DoDeliver(int len, const u_char* data)
break;
default:
internal_error("bad state in Contents_Rlogin_Analyzer::DoDeliver");
bro_logger->InternalError("bad state in Contents_Rlogin_Analyzer::DoDeliver");
break;
}
}
@ -223,7 +223,7 @@ Rlogin_Analyzer::Rlogin_Analyzer(Connection* conn)
void Rlogin_Analyzer::ClientUserName(const char* s)
{
if ( client_name )
internal_error("multiple rlogin client names");
bro_logger->InternalError("multiple rlogin client names");
client_name = new StringVal(s);
}

View file

@ -113,7 +113,7 @@ bool RuleConditionPayloadSize::DoMatch(Rule* rule, RuleEndpointState* state,
return payload_size >= val;
default:
internal_error("unknown comparision type");
bro_logger->InternalError("unknown comparision type");
}
// Should not be reached
@ -135,7 +135,7 @@ bool RuleConditionEval::DoMatch(Rule* rule, RuleEndpointState* state,
{
if ( ! id->HasVal() )
{
run_time("undefined value");
bro_logger->Error("undefined value");
return false;
}

View file

@ -10,6 +10,7 @@
#include "NetVar.h"
#include "Scope.h"
#include "File.h"
#include "Logger.h"
// FIXME: Things that are not fully implemented/working yet:
//
@ -200,7 +201,7 @@ bool RuleMatcher::ReadFiles(const name_list& files)
rules_in = search_for_file( files[i], "sig", 0, false);
if ( ! rules_in )
{
error("Can't open signature file", files[i]);
bro_logger->Error("Can't open signature file", files[i]);
return false;
}
@ -400,7 +401,7 @@ static inline uint32 getval(const u_char* data, int size)
return ntohl(*(uint32*) data);
default:
internal_error("illegal HdrTest size");
bro_logger->InternalError("illegal HdrTest size");
}
// Should not be reached.
@ -513,7 +514,7 @@ RuleEndpointState* RuleMatcher::InitEndpoint(Analyzer* analyzer,
default:
data = 0;
internal_error("unknown protocol");
bro_logger->InternalError("unknown protocol");
}
// ### data can be nil here if it's an
@ -542,7 +543,7 @@ RuleEndpointState* RuleMatcher::InitEndpoint(Analyzer* analyzer,
DO_MATCH_OR(*h->vals, getval(data + h->offset, h->size), >=);
default:
internal_error("unknown comparision type");
bro_logger->InternalError("unknown comparision type");
}
no_match:
@ -569,7 +570,7 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
{
if ( ! state )
{
warn("RuleEndpointState not initialized yet.");
bro_logger->Warning("RuleEndpointState not initialized yet.");
return;
}

View file

@ -6,6 +6,7 @@
#include "SMB.h"
#include "smb_pac.h"
#include "Val.h"
#include "Logger.h"
namespace {
const bool DEBUG_smb_ipc = true;
@ -732,7 +733,7 @@ int SMB_Session::ParseTransaction(int is_orig, int cmd,
break;
default:
internal_error("command mismatch for ParseTransaction");
bro_logger->InternalError("command mismatch for ParseTransaction");
}
int ret;
@ -932,7 +933,7 @@ void SMB_Session::Weird(const char* msg)
// input can be in Unicode (little endian), and the returned string
// will be in ASCII. Note, Unicode strings have NUL characters
// at the end of them already. Adding an additional NUL byte at
// the end leads to embedded-NUL warnings (CheckString() run_time error).
// the end leads to embedded-NUL warnings (CheckString() run time error).
BroString* SMB_Session::ExtractString(binpac::SMB::SMB_string const* s)
{

View file

@ -10,6 +10,7 @@
#include "SMTP.h"
#include "Event.h"
#include "ContentLine.h"
#include "Logger.h"
#undef SMTP_CMD_DEF
#define SMTP_CMD_DEF(cmd) #cmd,
@ -865,7 +866,7 @@ void SMTP_Analyzer::BeginData()
skip_data = 0; // reset the flag at the beginning of the mail
if ( mail != 0 )
{
warn("nested mail transaction");
bro_logger->Warning("nested mail transaction");
mail->Done();
delete mail;
}
@ -876,7 +877,7 @@ void SMTP_Analyzer::BeginData()
void SMTP_Analyzer::EndData()
{
if ( ! mail )
warn("Unmatched end of data");
bro_logger->Warning("Unmatched end of data");
else
{
mail->Done();

View file

@ -1,5 +1,6 @@
#include "SSL-binpac.h"
#include "TCP_Reassembler.h"
#include "Logger.h"
#include "util.h"
@ -54,7 +55,7 @@ void SSL_Analyzer_binpac::Undelivered(int seq, int len, bool orig)
void SSL_Analyzer_binpac::warn_(const char* msg)
{
warn("SSL_Analyzer_binpac: ", msg);
bro_logger->Warning("SSL_Analyzer_binpac: ", msg);
}
void SSL_Analyzer_binpac::generate_warnings()

946
src/SSLv2.cc Normal file
View file

@ -0,0 +1,946 @@
// $Id: SSLv2.cc 5988 2008-07-19 07:02:12Z vern $
#include "SSLv2.h"
#include "SSLv3.h"
// --- Initalization of static variables --------------------------------------
uint SSLv2_Interpreter::totalConnections = 0;
uint SSLv2_Interpreter::analyzedConnections = 0;
uint SSLv2_Interpreter::openedConnections = 0;
uint SSLv2_Interpreter::failedConnections = 0;
uint SSLv2_Interpreter::weirdConnections = 0;
uint SSLv2_Interpreter::totalRecords = 0;
uint SSLv2_Interpreter::clientHelloRecords = 0;
uint SSLv2_Interpreter::serverHelloRecords = 0;
uint SSLv2_Interpreter::clientMasterKeyRecords = 0;
uint SSLv2_Interpreter::errorRecords = 0;
// --- SSLv2_Interpreter -------------------------------------------------------
/*!
* The Constructor.
*
* \param proxy Pointer to the SSLProxy_Analyzer who created this instance.
*/
SSLv2_Interpreter::SSLv2_Interpreter(SSLProxy_Analyzer* proxy)
: SSL_Interpreter(proxy)
{
++totalConnections;
records = 0;
bAnalyzedCounted = false;
connState = START;
pServerCipherSpecs = 0;
pClientCipherSpecs = 0;
bClientWantsCachedSession = false;
usedCipherSpec = (SSLv2_CipherSpec) 0;
pConnectionId = 0;
pChallenge = 0;
pSessionId = 0;
pMasterClearKey = 0;
pMasterEncryptedKey = 0;
pClientReadKey = 0;
pServerReadKey = 0;
}
/*!
* The Destructor.
*/
SSLv2_Interpreter::~SSLv2_Interpreter()
{
if ( connState != CLIENT_MASTERKEY_SEEN &&
connState != CACHED_SESSION &&
connState != START && // we only complain if we saw some data
connState != ERROR_SEEN )
++failedConnections;
if ( connState != CLIENT_MASTERKEY_SEEN && connState != CACHED_SESSION )
++weirdConnections;
delete pServerCipherSpecs;
delete pClientCipherSpecs;
delete pConnectionId;
delete pChallenge;
delete pSessionId;
delete pMasterClearKey;
delete pMasterEncryptedKey;
delete pClientReadKey;
delete pServerReadKey;
}
/*!
* This method implements SSL_Interpreter::BuildInterpreterEndpoints()
*/
void SSLv2_Interpreter::BuildInterpreterEndpoints()
{
orig = new SSLv2_Endpoint(this, 1);
resp = new SSLv2_Endpoint(this, 0);
}
/*!
* This method prints some counters.
*/
void SSLv2_Interpreter::printStats()
{
printf("SSLv2:\n");
printf("totalConnections = %u\n", totalConnections);
printf("analyzedConnections = %u\n", analyzedConnections);
printf("openedConnections = %u\n", openedConnections);
printf("failedConnections = %u\n", failedConnections);
printf("weirdConnections = %u\n", weirdConnections);
printf("totalRecords = %u\n", totalRecords);
printf("clientHelloRecords = %u\n", clientHelloRecords);
printf("serverHelloRecords = %u\n", serverHelloRecords);
printf("clientMasterKeyRecords = %u\n", clientMasterKeyRecords);
printf("errorRecords = %u\n", errorRecords);
printf("SSL_RecordBuilder::maxAllocCount = %u\n", SSL_RecordBuilder::maxAllocCount);
printf("SSL_RecordBuilder::maxFragmentCount = %u\n", SSL_RecordBuilder::maxFragmentCount);
printf("SSL_RecordBuilder::fragmentedHeaders = %u\n", SSL_RecordBuilder::fragmentedHeaders);
}
/*!
* \return the current state of the ssl connection
*/
SSLv2_States SSLv2_Interpreter::ConnState()
{
return connState;
}
/*!
* This method is called by SSLv2_Endpoint::Deliver(). It is the main entry
* point of this class. The header of the given SSLV2 record is analyzed and
* its contents are then passed to the corresponding analyzer method. After
* the record has been analyzed, the ssl connection state is updated.
*
* \param s Pointer to the endpoint which sent the record
* \param length length of SSLv2 record
* \param data pointer to SSLv2 record to analyze
*/
void SSLv2_Interpreter::NewSSLRecord(SSL_InterpreterEndpoint* s,
int length, const u_char* data)
{
++records;
++totalRecords;
if ( ! bAnalyzedCounted )
{
++analyzedConnections;
bAnalyzedCounted = true;
}
// We should see a maximum of 4 cleartext records.
if ( records == 5 )
{ // so this should never happen
Weird("SSLv2: Saw more than 4 records, skipping connection...");
proxy->SetSkip(1);
return;
}
// SSLv2 record header analysis
uint32 recordLength = 0; // data length of SSLv2 record
bool isEscape = false;
uint8 padding = 0;
const u_char* contents;
if ( (data[0] & 0x80) > 0 )
{ // we have a two-byte record header
recordLength = ((data[0] & 0x7f) << 8) | data[1];
contents = data + 2;
if ( recordLength + 2 != uint32(length) )
{
// This should never happen, otherwise
// we have a bug in the SSL_RecordBuilder.
Weird("SSLv2: FATAL: recordLength doesn't match data block length!");
connState = ERROR_REQUIRED;
proxy->SetSkip(1);
return;
}
}
else
{ // We have a three-byte record header.
recordLength = ((data[0] & 0x3f) << 8) | data[1];
isEscape = (data[0] & 0x40) != 0;
padding = data[2];
contents = data + 3;
if ( recordLength + 3 != uint32(length) )
{
// This should never happen, otherwise
// we have a bug in the SSL_RecordBuilder.
Weird("SSLv2: FATAL: recordLength doesn't match data block length!");
connState = ERROR_REQUIRED;
proxy->SetSkip(1);
return;
}
if ( padding == 0 && ! isEscape )
Weird("SSLv2: 3 Byte record header, but no escape, no padding!");
}
if ( recordLength == 0 )
{
Weird("SSLv2: Record length is zero (no record data)!");
return;
}
if ( isEscape )
Weird("SSLv2: Record has escape bit set (security escape)!");
if ( padding > 0 && connState != CACHED_SESSION &&
connState != CLIENT_MASTERKEY_SEEN )
Weird("SSLv2 record with padding > 0 in cleartext!");
// MISSING:
// A final consistency check is done when a block cipher is used
// and the protocol is using encryption. The amount of data present
// in a record (RECORD-LENGTH))must be a multiple of the cipher's
// block size. If the received record is not a multiple of the
// cipher's block size then the record is considered damaged, and it
// is to be treated as if an "I/O Error" had occurred (i.e. an
// unrecoverable error is asserted and the connection is closed).
switch ( connState ) {
case START:
// Only CLIENT-HELLLOs allowed here.
if ( contents[0] != SSLv2_MT_CLIENT_HELLO )
{
Weird("SSLv2: First packet is not a CLIENT-HELLO!");
analyzeRecord(s, recordLength, contents);
connState = ERROR_REQUIRED;
}
else
connState = ClientHelloRecord(s, recordLength, contents);
break;
case CLIENT_HELLO_SEEN:
// Only SERVER-HELLOs or ERRORs allowed here.
if ( contents[0] == SSLv2_MT_SERVER_HELLO )
connState = ServerHelloRecord(s, recordLength, contents);
else if ( contents[0] == SSLv2_MT_ERROR )
connState = ErrorRecord(s, recordLength, contents);
else
{
Weird("SSLv2: State violation in CLIENT_HELLO_SEEN!");
analyzeRecord(s, recordLength, contents);
connState = ERROR_REQUIRED;
}
break;
case NEW_SESSION:
// We expect a client master key.
if ( contents[0] == SSLv2_MT_CLIENT_MASTER_KEY )
connState = ClientMasterKeyRecord(s, recordLength, contents);
else if ( contents[0] == SSLv2_MT_ERROR )
connState = ErrorRecord(s, recordLength, contents);
else
{
Weird("SSLv2: State violation in NEW_SESSION or encrypted record!");
analyzeRecord(s, recordLength, contents);
connState = ERROR_REQUIRED;
}
delete pServerCipherSpecs;
pServerCipherSpecs = 0;
break;
case CACHED_SESSION:
delete pServerCipherSpecs;
pServerCipherSpecs = 0;
// No break here.
case CLIENT_MASTERKEY_SEEN:
// If no error record, no further analysis.
if ( contents[0] == SSLv2_MT_ERROR &&
recordLength == SSLv2_ERROR_RECORD_SIZE )
connState = ErrorRecord(s, recordLength, contents);
else
{
// So we finished the cleartext handshake.
// Skip all further data.
proxy->SetSkip(1);
++openedConnections;
}
break;
case ERROR_REQUIRED:
if ( contents[0] == SSLv2_MT_ERROR )
connState = ErrorRecord(s, recordLength, contents);
else
{
// We lost tracking: this should not happen.
Weird("SSLv2: State inconsistency in ERROR_REQUIRED (lost tracking!)!");
analyzeRecord(s, recordLength, contents);
connState = ERROR_REQUIRED;
}
break;
case ERROR_SEEN:
// We don't have recoverable errors in cleartext phase,
// so we shouldn't see anymore packets.
Weird("SSLv2: Traffic after error record!");
analyzeRecord(s, recordLength, contents);
break;
default:
bro_logger->InternalError("SSLv2: unknown state");
break;
}
}
/*!
* This method is called whenever the connection tracking failed. It calls
* the corresponding analyzer method for the given SSLv2 record, but does not
* update the ssl connection state.
*
* \param s Pointer to the endpoint which sent the record
* \param length length of SSLv2 record
* \param data pointer to SSLv2 record to analyze
*/
void SSLv2_Interpreter::analyzeRecord(SSL_InterpreterEndpoint* s,
int length, const u_char* data)
{
switch ( data[0] ) {
case SSLv2_MT_ERROR:
ErrorRecord(s, length, data);
break;
case SSLv2_MT_CLIENT_HELLO:
ClientHelloRecord(s, length, data);
break;
case SSLv2_MT_CLIENT_MASTER_KEY:
ClientMasterKeyRecord(s, length, data);
break;
case SSLv2_MT_SERVER_HELLO:
ServerHelloRecord(s, length, data);
break;
case SSLv2_MT_CLIENT_FINISHED:
case SSLv2_MT_SERVER_VERIFY:
case SSLv2_MT_SERVER_FINISHED:
case SSLv2_MT_REQUEST_CERTIFICATE:
case SSLv2_MT_CLIENT_CERTIFICATE:
Weird("SSLv2: Encrypted record type seems to be in cleartext");
break;
default:
// Unknown record type.
Weird("SSLv2: Unknown record type or encrypted record");
break;
}
}
/*!
* This method analyses a SSLv2 CLIENT-HELLO record.
*
* \param s Pointer to the endpoint which sent the record
* \param length length of SSLv2 CLIENT-HELLO record
* \param data pointer to SSLv2 CLIENT-HELLO record to analyze
*
* \return the updated state of the current ssl connection
*/
SSLv2_States SSLv2_Interpreter::ClientHelloRecord(SSL_InterpreterEndpoint* s,
int recordLength, const u_char* recordData)
{
// This method gets the record's data (without the header).
++clientHelloRecords;
if ( s != orig )
Weird("SSLv2: CLIENT-HELLO record from server!");
// There should not be any pending data in the SSLv2 reassembler,
// because the client should wait for a server response.
if ( ((SSLv2_Endpoint*) s)->isDataPending() )
Weird("SSLv2: Pending data in SSL_RecordBuilder after CLIENT-HELLO!");
// Client hello minimum header size check.
if ( recordLength < SSLv2_CLIENT_HELLO_HEADER_SIZE )
{
Weird("SSLv2: CLIENT-HELLO is too small!");
return ERROR_REQUIRED;
}
// Extract the data of the client hello header.
SSLv2_ClientHelloHeader ch;
ch.clientVersion = uint16(recordData[1] << 8) | recordData[2];
ch.cipherSpecLength = uint16(recordData[3] << 8) | recordData[4];
ch.sessionIdLength = uint16(recordData[5] << 8) | recordData[6];
ch.challengeLength = uint16(recordData[7] << 8) | recordData[8];
if ( ch.clientVersion != SSLProxy_Analyzer::SSLv20 &&
ch.clientVersion != SSLProxy_Analyzer::SSLv30 &&
ch.clientVersion != SSLProxy_Analyzer::SSLv31 )
{
Weird("SSLv2: Unsupported SSL-Version in CLIENT-HELLO");
return ERROR_REQUIRED;
}
if ( ch.challengeLength + ch.cipherSpecLength + ch.sessionIdLength +
SSLv2_CLIENT_HELLO_HEADER_SIZE != recordLength )
{
Weird("SSLv2: Size inconsistency in CLIENT-HELLO");
return ERROR_REQUIRED;
}
// The CIPHER-SPECS-LENGTH must be > 0 and a multiple of 3.
if ( ch.cipherSpecLength == 0 || ch.cipherSpecLength % 3 != 0 )
{
Weird("SSLv2: Nonconform CIPHER-SPECS-LENGTH in CLIENT-HELLO.");
return ERROR_REQUIRED;
}
// The SESSION-ID-LENGTH must either be zero or 16.
if ( ch.sessionIdLength != 0 && ch.sessionIdLength != 16 )
Weird("SSLv2: Nonconform SESSION-ID-LENGTH in CLIENT-HELLO.");
if ( (ch.challengeLength < 16) || (ch.challengeLength > 32))
Weird("SSLv2: Nonconform CHALLENGE-LENGTH in CLIENT-HELLO.");
const u_char* ptr = recordData;
ptr += SSLv2_CLIENT_HELLO_HEADER_SIZE + ch.cipherSpecLength;
pSessionId = new SSL_DataBlock(ptr, ch.sessionIdLength);
// If decrypting, store the challenge.
if ( ssl_store_key_material && ch.challengeLength <= 32 )
pChallenge = new SSL_DataBlock(ptr, ch.challengeLength);
bClientWantsCachedSession = ch.sessionIdLength != 0;
TableVal* currentCipherSuites =
analyzeCiphers(s, ch.cipherSpecLength,
recordData + SSLv2_CLIENT_HELLO_HEADER_SIZE);
fire_ssl_conn_attempt(ch.clientVersion, currentCipherSuites);
return CLIENT_HELLO_SEEN;
}
/*!
* This method analyses a SSLv2 SERVER-HELLO record.
*
* \param s Pointer to the endpoint which sent the record
* \param length length of SSLv2 SERVER-HELLO record
* \param data pointer to SSLv2 SERVER-HELLO record to analyze
*
* \return the updated state of the current ssl connection
*/
SSLv2_States SSLv2_Interpreter::ServerHelloRecord(SSL_InterpreterEndpoint* s,
int recordLength, const u_char* recordData)
{
++serverHelloRecords;
TableVal* currentCipherSuites = NULL;
if ( s != resp )
Weird("SSLv2: SERVER-HELLO from client!");
if ( recordLength < SSLv2_SERVER_HELLO_HEADER_SIZE )
{
Weird("SSLv2: SERVER-HELLO is too small!");
return ERROR_REQUIRED;
}
// Extract the data of the client hello header.
SSLv2_ServerHelloHeader sh;
sh.sessionIdHit = recordData[1];
sh.certificateType = recordData[2];
sh.serverVersion = uint16(recordData[3] << 8) | recordData[4];
sh.certificateLength = uint16(recordData[5] << 8) | recordData[6];
sh.cipherSpecLength = uint16(recordData[7] << 8) | recordData[8];
sh.connectionIdLength = uint16(recordData[9] << 8) | recordData[10];
if ( sh.serverVersion != SSLProxy_Analyzer::SSLv20 )
{
Weird("SSLv2: Unsupported SSL-Version in SERVER-HELLO");
return ERROR_REQUIRED;
}
if ( sh.certificateLength + sh.cipherSpecLength +
sh.connectionIdLength +
SSLv2_SERVER_HELLO_HEADER_SIZE != recordLength )
{
Weird("SSLv2: Size inconsistency in SERVER-HELLO");
return ERROR_REQUIRED;
}
// The length of the CONNECTION-ID must be between 16 and 32 bytes.
if ( sh.connectionIdLength < 16 || sh.connectionIdLength > 32 )
Weird("SSLv2: Nonconform CONNECTION-ID-LENGTH in SERVER-HELLO");
// If decrypting, store the connection ID.
if ( ssl_store_key_material && sh.connectionIdLength <= 32 )
{
const u_char* ptr = recordData;
ptr += SSLv2_SERVER_HELLO_HEADER_SIZE + sh.cipherSpecLength +
sh.certificateLength;
pConnectionId = new SSL_DataBlock(ptr, sh.connectionIdLength);
}
if ( sh.sessionIdHit == 0 )
{
// Generating reusing-connection event.
EventHandlerPtr event = ssl_session_insertion;
if ( event )
{
TableVal* sessionIDTable =
MakeSessionID(
recordData +
SSLv2_SERVER_HELLO_HEADER_SIZE +
sh.certificateLength +
sh.cipherSpecLength,
sh.connectionIdLength);
val_list* vl = new val_list;
vl->append(proxy->BuildConnVal());
vl->append(sessionIDTable);
proxy->ConnectionEvent(ssl_session_insertion, vl);
}
}
SSLv2_States nextState;
if ( sh.sessionIdHit != 0 )
{ // we're using a cached session
// There should not be any pending data in the SSLv2
// reassembler, because the server should wait for a
// client response.
if ( ((SSLv2_Endpoint*) s)->isDataPending() )
{
// But turns out some SSL Implementations do this
// when using a cached session.
}
// Consistency check for SESSION-ID-HIT.
if ( ! bClientWantsCachedSession )
Weird("SSLv2: SESSION-ID hit in SERVER-HELLO, but no SESSION-ID in CLIENT-HELLO!");
// If the SESSION-ID-HIT flag is non-zero then the
// CERTIFICATE-TYPE, CERTIFICATE-LENGTH and
// CIPHER-SPECS-LENGTH fields will be zero.
if ( sh.certificateType != 0 || sh.certificateLength != 0 ||
sh.cipherSpecLength != 0 )
Weird("SSLv2: SESSION-ID-HIT, but session data in SERVER-HELLO");
// Generate reusing-connection event.
if ( pSessionId )
{
fire_ssl_conn_reused(pSessionId);
delete pSessionId;
pSessionId = 0;
}
nextState = CACHED_SESSION;
}
else
{ // we're starting a new session
// There should not be any pending data in the SSLv2
// reassembler, because the server should wait for
// a client response.
if ( ((SSLv2_Endpoint*) s)->isDataPending() )
Weird("SSLv2: Pending data in SSL_RecordBuilder after SERVER-HELLO (new session)!");
// TODO: check certificate length ???
if ( sh.certificateLength == 0 )
Weird("SSLv2: No certificate in SERVER-HELLO!");
// The CIPHER-SPECS-LENGTH must be > zero and a multiple of 3.
if ( sh.cipherSpecLength == 0 )
Weird("SSLv2: No CIPHER-SPECS in SERVER-HELLO!");
if ( sh.cipherSpecLength % 3 != 0 )
{
Weird("SSLv2: Nonconform CIPHER-SPECS-LENGTH in SERVER-HELLO");
return ERROR_REQUIRED;
}
const u_char* ptr = recordData;
ptr += sh.certificateLength + SSLv2_SERVER_HELLO_HEADER_SIZE;
currentCipherSuites = analyzeCiphers(s, sh.cipherSpecLength, ptr);
nextState = NEW_SESSION;
}
// Check if at least one cipher is supported by the client.
if ( pClientCipherSpecs && pServerCipherSpecs )
{
bool bFound = false;
for ( int i = 0; i < pClientCipherSpecs->len; i += 3 )
{
for ( int j = 0; j < pServerCipherSpecs->len; j += 3 )
{
if ( memcmp(pClientCipherSpecs + i,
pServerCipherSpecs + j, 3) == 0 )
{
bFound = true;
i = pClientCipherSpecs->len;
break;
}
}
}
if ( ! bFound )
{
Weird("SSLv2: Client's and server's CIPHER-SPECS don't match!");
nextState = ERROR_REQUIRED;
}
delete pClientCipherSpecs;
pClientCipherSpecs = 0;
}
// Certificate analysis.
if ( sh.certificateLength > 0 && ssl_analyze_certificates != 0 )
{
analyzeCertificate(s, recordData + SSLv2_SERVER_HELLO_HEADER_SIZE,
sh.certificateLength, sh.certificateType, false);
}
if ( nextState == NEW_SESSION )
// generate server-reply event
fire_ssl_conn_server_reply(sh.serverVersion, currentCipherSuites);
else if ( nextState == CACHED_SESSION )
{ // generate server-reply event
fire_ssl_conn_server_reply(sh.serverVersion, currentCipherSuites);
// Generate a connection-established event with a dummy
// cipher suite, since we can't remember session information
// (yet).
// Note: A new session identifier is sent encrypted in SSLv2!
fire_ssl_conn_established(sh.serverVersion, 0xABCD);
}
else
// Unref, since the table is not delivered to any event.
Unref(currentCipherSuites);
return nextState;
}
/*!
* This method analyses a SSLv2 CLIENT-MASTER-KEY record.
*
* \param s Pointer to the endpoint which sent the record
* \param length length of SSLv2 CLIENT-MASTER-KEY record
* \param data pointer to SSLv2 CLIENT-MASTER-KEY record to analyze
*
* \return the updated state of the current ssl connection
*/
SSLv2_States SSLv2_Interpreter::
ClientMasterKeyRecord(SSL_InterpreterEndpoint* s, int recordLength,
const u_char* recordData)
{
++clientMasterKeyRecords;
SSLv2_States nextState = CLIENT_MASTERKEY_SEEN;
if ( s != orig )
Weird("SSLv2: CLIENT-MASTER-KEY from server!");
if ( recordLength < SSLv2_CLIENT_MASTER_KEY_HEADER_SIZE )
{
Weird("SSLv2: CLIENT-MASTER-KEY is too small!");
return ERROR_REQUIRED;
}
// Extract the data of the client master key header.
SSLv2_ClientMasterKeyHeader cmk;
cmk.cipherKind =
((recordData[1] << 16) | recordData[2] << 8) | recordData[3];
cmk.clearKeyLength = uint16(recordData[4] << 8) | recordData[5];
cmk.encryptedKeyLength = uint16(recordData[6] << 8) | recordData[7];
cmk.keyArgLength = uint16(recordData[8] << 8) | recordData[9];
if ( cmk.clearKeyLength + cmk.encryptedKeyLength + cmk.keyArgLength +
SSLv2_CLIENT_MASTER_KEY_HEADER_SIZE != recordLength )
{
Weird("SSLv2: Size inconsistency in CLIENT-MASTER-KEY");
return ERROR_REQUIRED;
}
// Check if cipher is supported by the server.
if ( pServerCipherSpecs )
{
bool bFound = false;
for ( int i = 0; i < pServerCipherSpecs->len; i += 3 )
{
uint32 cipherSpec =
((pServerCipherSpecs->data[i] << 16) |
pServerCipherSpecs->data[i+1] << 8) |
pServerCipherSpecs->data[i+2];
if ( cmk.cipherKind == cipherSpec )
{
bFound = true;
break;
}
}
if ( ! bFound )
{
Weird("SSLv2: Client chooses unadvertised cipher in CLIENT-MASTER-KEY!");
nextState = ERROR_REQUIRED;
}
else
nextState = CLIENT_MASTERKEY_SEEN;
delete pServerCipherSpecs;
pServerCipherSpecs = 0;
}
// TODO: check if cipher has been advertised before.
SSL_CipherSpec* pCipherSpecTemp = 0;
HashKey h(static_cast<bro_uint_t>(cmk.cipherKind));
pCipherSpecTemp = (SSL_CipherSpec*) SSL_CipherSpecDict.Lookup(&h);
if ( ! pCipherSpecTemp || ! (pCipherSpecTemp->flags & SSL_FLAG_SSLv20) )
Weird("SSLv2: Unknown CIPHER-SPEC in CLIENT-MASTER-KEY!");
else
{ // check for conistency of clearKeyLength
if ( cmk.clearKeyLength * 8 != pCipherSpecTemp->clearKeySize )
{
Weird("SSLv2: Inconsistency of clearKeyLength in CLIENT-MASTER-KEY!");
// nextState = ERROR_REQUIRED;
}
// TODO: check for consistency of encryptedKeyLength.
// TODO: check for consistency of keyArgLength.
// switch ( cmk.cipherKind )
// {
// case SSL_CK_RC4_128_WITH_MD5:
// case SSL_CK_RC4_128_EXPORT40_WITH_MD5:
// if ( cmk.keyArgLength != 0 )
// {
// Weird("SSLv2: Inconsistency of keyArgLength in CLIENT-MASTER-KEY!");
// //nextState = ERROR_REQUIRED;
// }
// break;
// case SSL_CK_DES_64_CBC_WITH_MD5:
// case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5:
// case SSL_CK_RC2_128_CBC_WITH_MD5:
// case SSL_CK_IDEA_128_CBC_WITH_MD5:
// case SSL_CK_DES_192_EDE3_CBC_WITH_MD5:
// if ( cmk.keyArgLength != 8 )
// {
// Weird("SSLv2: Inconsistency of keyArgLength in CLIENT-MASTER-KEY!");
// }
// break;
// }
}
// Remember the used cipher spec.
usedCipherSpec = SSLv2_CipherSpec(cmk.cipherKind);
// If decrypting, store the clear key part of the master key.
if ( ssl_store_key_material /* && cmk.clearKeyLength == 11 */ )
{
pMasterClearKey =
new SSL_DataBlock((recordData + SSLv2_CLIENT_MASTER_KEY_HEADER_SIZE), cmk.clearKeyLength);
pMasterEncryptedKey =
new SSL_DataBlock((recordData + SSLv2_CLIENT_MASTER_KEY_HEADER_SIZE + cmk.clearKeyLength ), cmk.encryptedKeyLength);
}
if ( nextState == CLIENT_MASTERKEY_SEEN )
fire_ssl_conn_established(SSLProxy_Analyzer::SSLv20,
cmk.cipherKind);
return nextState;
}
/*!
* This method analyses a SSLv2 ERROR record.
*
* \param s Pointer to the endpoint which sent the record
* \param length length of SSLv2 ERROR record
* \param data pointer to SSLv2 ERROR record to analyze
*
* \return the updated state of the current ssl connection
*/
SSLv2_States SSLv2_Interpreter::ErrorRecord(SSL_InterpreterEndpoint* s,
int recordLength, const u_char* recordData)
{
++errorRecords;
if ( unsigned(recordLength) != SSLv2_ERROR_RECORD_SIZE )
{
Weird("SSLv2: Size mismatch in Error Record!");
return ERROR_REQUIRED;
}
SSLv2_ErrorRecord er;
er.errorCode = (recordData[1] << 8) | recordData[2];
SSL3x_AlertLevel al = SSL3x_AlertLevel(255);
switch ( er.errorCode ) {
case SSLv2_PE_NO_CIPHER:
// The client doesn't support a cipher which the server
// supports. Only from client to server and not recoverable!
al = SSL3x_ALERT_LEVEL_FATAL;
break;
case SSLv2_PE_NO_CERTIFICATE:
if ( s == orig )
// from client to server: not recoverable
al = SSL3x_ALERT_LEVEL_FATAL;
else
// from server to client: recoverable
al = SSL3x_ALERT_LEVEL_WARNING;
break;
case SSLv2_PE_BAD_CERTIFICATE:
if ( s == orig )
// from client to server: not recoverable
al = SSL3x_ALERT_LEVEL_FATAL;
else
// from server to client: recoverable
al = SSL3x_ALERT_LEVEL_WARNING;
break;
case SSLv2_PE_UNSUPPORTED_CERTIFICATE_TYPE:
if ( s == orig )
// from client to server: not recoverable
al = SSL3x_ALERT_LEVEL_FATAL;
else
// from server to client: recoverable
al = SSL3x_ALERT_LEVEL_WARNING;
break;
default:
al = SSL3x_ALERT_LEVEL_FATAL;
break;
}
fire_ssl_conn_alert(SSLProxy_Analyzer::SSLv20, al, er.errorCode);
return ERROR_SEEN;
}
/*!
* This method analyses a set of SSLv2 cipher suites.
*
* \param s Pointer to the endpoint which sent the cipher suites
* \param length length of cipher suites
* \param data pointer to cipher suites to analyze
*
* \return a pointer to a Bro TableVal (of type cipher_suites_list) which contains
* the cipher suites list of the current analyzed record
*/
TableVal* SSLv2_Interpreter::analyzeCiphers(SSL_InterpreterEndpoint* s,
int length, const u_char* data)
{
if ( length > MAX_CIPHERSPEC_SIZE )
{
if ( s == orig )
Weird("SSLv2: Client has CipherSpecs > MAX_CIPHERSPEC_SIZE");
else
Weird("SSLv2: Server has CipherSpecs > MAX_CIPHERSPEC_SIZE");
}
else
{ // cipher specs are not too big
if ( ssl_compare_cipherspecs )
{ // store cipher specs for state analysis
if ( s == resp )
pServerCipherSpecs =
new SSL_DataBlock(data, length);
else
pClientCipherSpecs =
new SSL_DataBlock(data, length);
}
}
const u_char* pCipher = data;
bool bExtractCipherSuite = false;
TableVal* pCipherTable = 0;
// We only extract the cipher suite when the corresponding
// ssl events are defined (otherwise we do work for nothing
// and suffer a memory leak).
// FIXME: This check needs to be done only once!
if ( (s == orig && ssl_conn_attempt) ||
(s == resp && ssl_conn_server_reply) )
{
pCipherTable = new TableVal(cipher_suites_list);
bExtractCipherSuite = true;
}
for ( int i = 0; i < length; i += 3 )
{
SSL_CipherSpec* pCurrentCipherSpec;
uint32 cipherSpecID =
((pCipher[0] << 16) | pCipher[1] << 8) | pCipher[2];
// Check for unknown cipher specs.
HashKey h(static_cast<bro_uint_t>(cipherSpecID));
pCurrentCipherSpec =
(SSL_CipherSpec*) SSL_CipherSpecDict.Lookup(&h);
if ( ! pCurrentCipherSpec )
{
if ( s == orig )
Weird("SSLv2: Unknown CIPHER-SPEC in CLIENT-HELLO!");
else
Weird("SSLv2: Unknown CIPHER-SPEC in SERVER-HELLO!");
}
if ( bExtractCipherSuite )
{
Val* index = new Val(cipherSpecID, TYPE_COUNT);
pCipherTable->Assign(index, 0);
Unref(index);
}
pCipher += 3;
}
return pCipherTable;
}
// --- SSLv2_EndPoint ---------------------------------------------------------
/*!
* The constructor.
*
* \param interpreter Pointer to the SSLv2 interpreter to whom this endpoint belongs to
* \param is_orig true if this is the originating endpoint of the ssl connection,
* false otherwise
*/
SSLv2_Endpoint::SSLv2_Endpoint(SSLv2_Interpreter* interpreter, int is_orig)
: SSL_InterpreterEndpoint(interpreter, is_orig)
{
sentRecords = 0;
}
/*!
* The destructor.
*/
SSLv2_Endpoint::~SSLv2_Endpoint()
{
}
/*!
* This method is called by the SSLProxy_Analyzer with a complete reassembled
* SSLv2 record. It passes the record to SSLv2_Interpreter::NewSSLRecord().
*
* \param t <b>reserved</b> (always zero)
* \param seq <b>reserved</b> (always zero)
* \param len length of the data block containing the ssl record
* \param data pointer to the data block containing the ssl record
*/
void SSLv2_Endpoint::Deliver(int len, const u_char* data)
{
++((SSLv2_Endpoint*)peer)->sentRecords;
((SSLv2_Interpreter*)interpreter)->NewSSLRecord(this, len, data);
}

View file

@ -7,6 +7,7 @@
#include "ID.h"
#include "Val.h"
#include "Scope.h"
#include "Logger.h"
static scope_list scopes;
static Scope* top_scope;
@ -27,7 +28,7 @@ Scope::Scope(ID* id)
if ( id_type->Tag() == TYPE_ERROR )
return;
else if ( id_type->Tag() != TYPE_FUNC )
internal_error("bad scope id");
bro_logger->InternalError("bad scope id");
Ref(id);
@ -128,7 +129,7 @@ ID* lookup_ID(const char* name, const char* curr_module, bool no_global,
if ( id )
{
if ( need_export && ! id->IsExport() && ! in_debug )
error("identifier is not exported:",
bro_logger->Error("identifier is not exported:",
fullname.c_str());
Ref(id);
@ -155,7 +156,7 @@ ID* install_ID(const char* name, const char* module_name,
bool is_global, bool is_export)
{
if ( scopes.length() == 0 && ! is_global )
internal_error("local identifier in global scope");
bro_logger->InternalError("local identifier in global scope");
IDScope scope;
if ( is_export || ! module_name ||
@ -197,7 +198,7 @@ Scope* pop_scope()
{
int n = scopes.length() - 1;
if ( n < 0 )
internal_error("scope underflow");
bro_logger->InternalError("scope underflow");
scopes.remove_nth(n);
Scope* old_top = top_scope;

View file

@ -21,7 +21,7 @@ SerialObj* SerialObj::Instantiate(SerialType type)
return o;
}
run_time(fmt("Unknown object type 0x%08x", type));
bro_logger->Error(fmt("Unknown object type 0x%08x", type));
return 0;
}
@ -31,7 +31,7 @@ const char* SerialObj::ClassName(SerialType type)
if ( f != names->end() )
return f->second;
run_time(fmt("Unknown object type 0x%08x", type));
bro_logger->Error(fmt("Unknown object type 0x%08x", type));
return "<no-class-name>";
}
@ -47,7 +47,7 @@ void SerialObj::Register(SerialType type, FactoryFunc f, const char* name)
FactoryMap::iterator i = factories->find(type);
if ( i != factories->end() )
internal_error("SerialType 0x%08x registered twice", type);
bro_logger->InternalError("SerialType 0x%08x registered twice", type);
(*factories)[type] = f;
(*names)[type] = name;
@ -77,7 +77,7 @@ bool SerialObj::Serialize(SerialInfo* info) const
const TransientID* tid = GetTID();
if ( ! tid )
internal_error("no tid - missing DECLARE_SERIAL?");
bro_logger->InternalError("no tid - missing DECLARE_SERIAL?");
if ( info->cache )
pid = info->s->Cache()->Lookup(*tid);
@ -211,7 +211,7 @@ SerialObj* SerialObj::Unserialize(UnserialInfo* info, SerialType type)
const TransientID* tid = obj->GetTID();
if ( ! tid )
internal_error("no tid - missing DECLARE_SERIAL?");
bro_logger->InternalError("no tid - missing DECLARE_SERIAL?");
if ( info->cache )
info->s->Cache()->Register(obj, pid, info->new_cache_strategy);

View file

@ -151,7 +151,7 @@ SERIAL_EXPR(VECTOR_COERCE_EXPR, 44)
#define SERIAL_STMT(name, val) SERIAL_CONST(name, val, STMT)
SERIAL_STMT(STMT, 1)
SERIAL_STMT(EXPR_LIST_STMT, 2)
SERIAL_STMT(ALARM_STMT, 3)
// There used to be ALARM_STMT (3) here.
SERIAL_STMT(PRINT_STMT, 4)
SERIAL_STMT(EXPR_STMT, 5)
SERIAL_STMT(IF_STMT, 6)

View file

@ -5,6 +5,7 @@
#include "net_util.h"
#include "SerializationFormat.h"
#include "Serializer.h"
#include "Logger.h"
SerializationFormat::SerializationFormat()
{
@ -58,7 +59,7 @@ bool SerializationFormat::ReadData(void* b, size_t count)
{
if ( input_pos + count > input_len )
{
error("data underflow during read in binary format");
bro_logger->Error("data underflow during read in binary format");
abort();
return false;
}
@ -204,7 +205,7 @@ bool BinarySerializationFormat::Read(char** str, int* len, const char* tag)
for ( int i = 0; i < l; i++ )
if ( ! s[i] )
{
error("binary Format: string contains null; replaced by '_'");
bro_logger->Error("binary Format: string contains null; replaced by '_'");
s[i] = '_';
}
}
@ -332,61 +333,61 @@ XMLSerializationFormat::~XMLSerializationFormat()
bool XMLSerializationFormat::Read(int* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(uint16* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(uint32* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(int64* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(uint64* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(bool* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(double* d, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(char* v, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(char** str, int* len, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}
bool XMLSerializationFormat::Read(string* s, const char* tag)
{
internal_error("no reading of xml");
bro_logger->InternalError("no reading of xml");
return false;
}

View file

@ -911,7 +911,7 @@ bool FileSerializer::Read(UnserialInfo* info, const char* file, bool header)
void FileSerializer::ReportError(const char* str)
{
run_time(str);
bro_logger->Error(str);
}
void FileSerializer::GotID(ID* id, Val* val)
@ -971,7 +971,7 @@ ConversionSerializer::~ConversionSerializer()
bool ConversionSerializer::Convert(const char* file_in, const char* file_out)
{
internal_error("Error: Printing as XML is broken.");
bro_logger->InternalError("Error: Printing as XML is broken.");
if ( ! serout->Open(file_out, true) )
return false;
@ -1004,19 +1004,19 @@ void ConversionSerializer::GotFunctionCall(const char* name, double time,
void ConversionSerializer::GotID(ID* id, Val* val)
{
warn("ConversionSerializer::GotID not implemented");
bro_logger->Warning("ConversionSerializer::GotID not implemented");
Unref(id);
}
void ConversionSerializer::GotStateAccess(StateAccess* s)
{
warn("ConversionSerializer::GotID not implemented");
bro_logger->Warning("ConversionSerializer::GotID not implemented");
delete s;
}
void ConversionSerializer::GotPacket(Packet* p)
{
warn("ConversionSerializer::GotPacket not implemented");
bro_logger->Warning("ConversionSerializer::GotPacket not implemented");
delete p;
}

Some files were not shown because too many files have changed in this diff Show more