Add new Session base class

This is mostly code copied from the existing Connection class, as that class now
inherits from Session.
This commit is contained in:
Tim Wojtulewicz 2021-03-08 12:34:45 -07:00
parent c752d76052
commit 8fbab9408a
8 changed files with 618 additions and 319 deletions

View file

@ -16,6 +16,7 @@
#include "zeek/WeirdState.h"
#include "zeek/ZeekArgs.h"
#include "zeek/IntrusivePtr.h"
#include "zeek/Session.h"
#include "zeek/iosource/Packet.h"
#include "zeek/analyzer/Tag.h"
@ -34,7 +35,6 @@ using RecordValPtr = IntrusivePtr<RecordVal>;
namespace detail {
class ConnectionTimer;
class Specific_RE_Matcher;
class RuleEndpointState;
class RuleHdrTest;
@ -55,8 +55,6 @@ enum ConnEventToFlag {
NUM_EVENTS_TO_FLAG,
};
typedef void (Connection::*timer_func)(double t);
struct ConnID {
IPAddr src_addr;
IPAddr dst_addr;
@ -71,25 +69,29 @@ static inline int addr_port_canon_lt(const IPAddr& addr1, uint32_t p1,
return addr1 < addr2 || (addr1 == addr2 && p1 < p2);
}
class Connection final : public Obj {
class Connection final : public Session {
public:
Connection(NetSessions* s, const detail::ConnIDKey& k, double t, const ConnID* id,
uint32_t flow, const Packet* pkt);
~Connection() override;
// Invoked when an encapsulation is discovered. It records the
// encapsulation with the connection and raises a "tunnel_changed"
// event if it's different from the previous encapsulation (or the
// first encountered). encap can be null to indicate no
// encapsulation.
/**
* Invoked when an encapsulation is discovered. It records the encapsulation
* with the connection and raises a "tunnel_changed" event if it's different
* from the previous encapsulation or if it's the first one encountered.
*
* @param encap The new encapsulation. Can be set to null to indicated no
* encapsulation or clear an old one.
*/
void CheckEncapsulation(const std::shared_ptr<EncapsulationStack>& encap);
// Invoked when connection is about to be removed. Use Ref(this)
// inside Done to keep the connection object around (though it'll
// no longer be accessible from the dictionary of active
// connections).
void Done();
/**
* Invoked when the session is about to be removed. Use Ref(this)
* inside Done to keep the session object around, though it'll
* no longer be accessible from the SessionManager.
*/
void Done() override;
// Process the connection's next packet. "data" points just
// beyond the IP header. It's updated to point just beyond
@ -111,13 +113,10 @@ public:
// connection is in the session map. If it is removed, the key
// should be marked invalid.
const detail::ConnIDKey& Key() const { return key; }
void ClearKey() { key_valid = false; }
bool IsKeyValid() const { return key_valid; }
double StartTime() const { return start_time; }
void SetStartTime(double t) { start_time = t; }
double LastTime() const { return last_time; }
void SetLastTime(double t) { last_time = t; }
detail::SessionKey SessionKey(bool copy) const override
{ return detail::SessionKey{&key, sizeof(key), copy}; }
void ClearKey() override { key_valid = false; }
bool IsKeyValid() const override { return key_valid; }
const IPAddr& OrigAddr() const { return orig_addr; }
const IPAddr& RespAddr() const { return resp_addr; }
@ -133,23 +132,6 @@ public:
TransportProto ConnTransport() const { return proto; }
// True if we should record subsequent packets (either headers or
// in their entirety, depending on record_contents). We still
// record subsequent SYN/FIN/RST, regardless of how this is set.
bool RecordPackets() const { return record_packets; }
void SetRecordPackets(bool do_record) { record_packets = do_record ? 1 : 0; }
// True if we should record full packets for this connection,
// false if we should just record headers.
bool RecordContents() const { return record_contents; }
void SetRecordContents(bool do_record) { record_contents = do_record ? 1 : 0; }
// Set whether to record *current* packet header/full.
void SetRecordCurrentPacket(bool do_record)
{ record_current_packet = do_record ? 1 : 0; }
void SetRecordCurrentContent(bool do_record)
{ record_current_content = do_record ? 1 : 0; }
// FIXME: Now this is in Analyzer and should eventually be removed here.
//
// If true, skip processing of remainder of connection. Note
@ -158,26 +140,19 @@ public:
void SetSkip(bool do_skip) { skip = do_skip ? 1 : 0; }
bool Skipping() const { return skip; }
// Arrange for the connection to expire after the given amount of time.
void SetLifetime(double lifetime);
// Returns true if the packet reflects a reuse of this
// connection (i.e., not a continuation but the beginning of
// a new connection).
bool IsReuse(double t, const u_char* pkt);
// Get/set the inactivity timeout for this connection.
void SetInactivityTimeout(double timeout);
double InactivityTimeout() const { return inactivity_timeout; }
// Activate connection_status_update timer.
void EnableStatusUpdateTimer();
/**
* Returns the associated "connection" record.
*/
const RecordValPtr& ConnVal();
const RecordValPtr& ConnVal() override;
/**
* Append additional entries to the history field in the connection record.
*/
void AppendAddl(const char* str);
void Match(detail::Rule::PatternType type, const u_char* data, int len,
@ -186,36 +161,11 @@ public:
/**
* Generates connection removal event(s).
*/
void RemovalEvent();
// If a handler exists for 'f', an event will be generated. If 'name' is
// given that event's first argument will be it, and it's second will be
// the connection value. If 'name' is null, then the event's first
// argument is the connection value.
void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, const char* name = nullptr);
/**
* Enqueues an event associated with this connection and given analyzer.
*/
void EnqueueEvent(EventHandlerPtr f, analyzer::Analyzer* analyzer,
Args args);
/**
* A version of EnqueueEvent() taking a variable number of arguments.
*/
template <class... Args>
std::enable_if_t<
std::is_convertible_v<
std::tuple_element_t<0, std::tuple<Args...>>, ValPtr>>
EnqueueEvent(EventHandlerPtr h, analyzer::Analyzer* analyzer, Args&&... args)
{ return EnqueueEvent(h, analyzer, zeek::Args{std::forward<Args>(args)...}); }
void RemovalEvent() override;
void Weird(const char* name, const char* addl = "", const char* source = "");
bool DidWeird() const { return weird != 0; }
// Cancel all associated timers.
void CancelTimers();
inline bool FlagEvent(ConnEventToFlag e)
{
if ( e >= 0 && e < NUM_EVENTS_TO_FLAG )
@ -234,8 +184,8 @@ public:
// Statistics.
// Just a lower bound.
unsigned int MemoryAllocation() const;
unsigned int MemoryAllocationConnVal() const;
unsigned int MemoryAllocation() const override;
unsigned int MemoryAllocationConnVal() const override;
static uint64_t TotalConnections()
{ return total_connections; }
@ -268,8 +218,6 @@ public:
void AddHistory(char code) { history += code; }
void DeleteTimer(double t);
// Sets the root of the analyzer tree as well as the primary PIA.
void SetRootAnalyzer(analyzer::TransportLayerAnalyzer* analyzer, analyzer::pia::PIA* pia);
analyzer::TransportLayerAnalyzer* GetRootAnalyzer() { return root_analyzer; }
@ -295,26 +243,10 @@ public:
protected:
// Add the given timer to expire at time t. If do_expire
// is true, then the timer is also evaluated when Bro terminates,
// otherwise not.
void AddTimer(timer_func timer, double t, bool do_expire,
detail::TimerType type);
void RemoveTimer(detail::Timer* t);
// Allow other classes to access pointers to these:
friend class detail::ConnectionTimer;
void InactivityTimer(double t);
void StatusUpdateTimer(double t);
void RemoveConnectionTimer(double t);
friend class detail::SessionTimer;
NetSessions* sessions;
detail::ConnIDKey key;
bool key_valid;
TimerPList timers;
IPAddr orig_addr;
IPAddr resp_addr;
@ -324,59 +256,30 @@ protected:
uint32_t vlan, inner_vlan; // VLAN this connection traverses, if available
u_char orig_l2_addr[Packet::L2_ADDR_LEN]; // Link-layer originator address, if available
u_char resp_l2_addr[Packet::L2_ADDR_LEN]; // Link-layer responder address, if available
double start_time, last_time;
double inactivity_timeout;
int suppress_event; // suppress certain events to once per conn.
RecordValPtr conn_val;
std::shared_ptr<EncapsulationStack> encapsulation; // tunnels
int suppress_event; // suppress certain events to once per conn.
unsigned int installed_status_timer:1;
unsigned int timers_canceled:1;
unsigned int is_active:1;
detail::ConnIDKey key;
bool key_valid;
unsigned int skip:1;
unsigned int weird:1;
unsigned int finished:1;
unsigned int record_packets:1, record_contents:1;
unsigned int record_current_packet:1, record_current_content:1;
unsigned int saw_first_orig_packet:1, saw_first_resp_packet:1;
// Count number of connections.
static uint64_t total_connections;
static uint64_t current_connections;
std::string history;
uint32_t hist_seen;
std::string history;
analyzer::TransportLayerAnalyzer* root_analyzer;
analyzer::pia::PIA* primary_PIA;
UID uid; // Globally unique connection ID.
detail::WeirdStateMap weird_state;
// Count number of connections.
static uint64_t total_connections;
static uint64_t current_connections;
};
namespace detail {
class ConnectionTimer final : public Timer {
public:
ConnectionTimer(Connection* arg_conn, timer_func arg_timer,
double arg_t, bool arg_do_expire, TimerType arg_type)
: Timer(arg_t, arg_type)
{ Init(arg_conn, arg_timer, arg_do_expire); }
~ConnectionTimer() override;
void Dispatch(double t, bool is_expire) override;
protected:
void Init(Connection* conn, timer_func timer, bool do_expire);
Connection* conn;
timer_func timer;
bool do_expire;
};
} // namespace detail
} // namespace zeek
#define ADD_TIMER(timer, t, do_expire, type) \
AddTimer(timer_func(timer), (t), (do_expire), (type))