winix/core/ipban.h

149 lines
2.9 KiB
C

/*
* This file is a part of Winix
* and is not publicly distributed
*
* Copyright (c) 2012, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfile_winix_core_ipban
#define headerfile_winix_core_ipban
// telling if the IPBan record is active
// we have two records: active and non active
// non active records is something like a history
// it is used to remember the last ban level
// so based on this in the future a next greater ban can be calculated
#define WINIX_IPBAN_FLAG_ACTIVE 1
// current ban level
// (if one of these flag is set and the record is active then it means the IP is banned at the moment)
// level 1: banned for short time
// level 2: can be set after level 1 has expired and the attacker still have not given up
// banned for some longer time in level 1
// level 3: can be set after level 2
// banned for much more time
#define WINIX_IPBAN_FLAG_BAN_LEVEL1 2
#define WINIX_IPBAN_FLAG_BAN_LEVEL2 4
#define WINIX_IPBAN_FLAG_BAN_LEVEL3 8
/*
struct defining some restrictions to an IP address
*/
struct IPBan
{
// at the moment only IPv4 are supported
int ip;
// one or more flags from WINIX_IPBAN_FLAG_*
int flags;
// when this record was last used
time_t last_used;
// when the restrictions (ban) should be removed
// valid only if some of WINIX_IPBAN_FLAG_BAN_LEVELX flags are set
// actually we do not remove the record but unsets WINIX_IPBAN_FLAG_ACTIVE flag
// so in the future we can check whether we need to change
// the ban level to a greater value
time_t expires;
// how many incorrect login attempts there are
unsigned int incorrect_login_events;
// in the future there can be more *_events fields
bool HasFlag(int flag) const
{
return (flags & flag) != 0;
}
void SetFlag(int flag)
{
flags = flags | flag;
}
void ClearFlag(int flag)
{
flags = flags & (~flag);
}
bool IsIPBanned() const
{
if( !HasFlag(WINIX_IPBAN_FLAG_ACTIVE) )
return false;
return HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL1) ||
HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL2) ||
HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL3);
}
void AddNextBanLevel(time_t level1_expires, time_t level2_expires, time_t level3_expires)
{
if( HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL3) )
{
expires = level3_expires;
return;
}
else
if( HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL2) )
{
SetFlag(WINIX_IPBAN_FLAG_BAN_LEVEL3);
expires = level3_expires;
return;
}
else
if( HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL1) )
{
SetFlag(WINIX_IPBAN_FLAG_BAN_LEVEL2);
expires = level2_expires;
return;
}
else
{
SetFlag(WINIX_IPBAN_FLAG_BAN_LEVEL1);
expires = level1_expires;
}
}
IPBan()
{
Clear();
}
void Clear()
{
ip = 0;
flags = 0;
last_used = 0;
expires = 0;
incorrect_login_events = 0;
}
void ClearAfterRemovingBan()
{
ClearFlag(WINIX_IPBAN_FLAG_ACTIVE);
incorrect_login_events = 0;
expires = 0;
}
};
#endif