public void Connection(Socket socket, EndPoint ip, Revision revision, Crypto crypto) { long id = this.GetNextID(); //every socket have their own unique id SocketsConnection connection = new SocketsConnection(id, socket, ip); //for easy to use if (AntiDDoSManager.OnConnection(connection)) //not blocked { if (this.Connections.TryAdd(id, connection)) { Skylight.GetGame().GetGameClientManager().Connection(connection, revision, crypto); if (Skylight.GetConfig()["emu.messages.connections"] == "1") { Logging.WriteLine(">> Connection [" + id + "] from [" + connection.GetIP() + "]"); } } else { connection.Disconnect("Connection TryAdd failed"); } } else { connection.Disconnect("Temp blocked IP"); } }
public static void OnDisconnect(SocketsConnection connection) { ConcurrentDictionary <long, SocketsConnection> connectionsOpen = null; if (AntiDDoSManager.ConnectionsOpenByIP.TryGetValue(connection.GetIP(), out connectionsOpen)) //in list { SocketsConnection connection_; connectionsOpen.TryRemove(connection.GetID(), out connection_); } }
//return true if the connection is violationg connection limti public static bool IsViolatingConnectionLimit(SocketsConnection connection) { ConcurrentDictionary <long, SocketsConnection> connectionsOpen = null; if (AntiDDoSManager.ConnectionsOpenByIP.TryGetValue(connection.GetIP(), out connectionsOpen)) //not first connection { if (connectionsOpen.Count >= AntiDDoSManager.ConnectioLimitByIP) { return(true); } } else { connectionsOpen = new ConcurrentDictionary <long, SocketsConnection>(); AntiDDoSManager.ConnectionsOpenByIP.TryAdd(connection.GetIP(), connectionsOpen); } connectionsOpen.TryAdd(connection.GetID(), connection); return(false); }
//return false if the connection shoudn't be accepted public static bool OnConnection(SocketsConnection connection) { if (AntiDDoSManager.DDoSProtectionEnabled) { string ip = connection.GetIP(); if (!AntiDDoSManager.IsIPTempBlock(ip)) //not blocked { if (!AntiDDoSManager.IsViolatingConnectionLimit(connection)) { return(true); } else { CacheItem failureCount = AntiDDoSManager.ConnectionLimitByIPViolationCounter.GetCacheItem(ip); if (failureCount == null) //havent violated in 5s { AntiDDoSManager.ConnectionLimitByIPViolationCounter.Set(ip, 1, DateTimeOffset.Now.AddSeconds(5)); //violating expires after 5s } else { AntiDDoSManager.ConnectionLimitByIPViolationCounter.Set(ip, ((int)failureCount.Value) + 1, DateTimeOffset.Now.AddSeconds(5)); if (((int)failureCount.Value) >= 5) //5 failures in 5s?!? I call DDoS { AntiDDoSManager.BlockForDDoS(ip); } } return(false); } } else { return(false); } } else { return(true); } }