|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Member
Iscritto dal: Jan 2010
Messaggi: 149
|
bannare un ip a tot connessioni in C#
Ciao a tutti vorrei riuscire a bloccare un determinato ip dopo che ha fatto
più connessioni tipo attacchi Ddos, e quindi bloccare ad un massimo di 20 connessioni. questo è il sorgente: class1.cs Codice:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ion.Storage;
using DOS.Storage;
using Holo.Virtual.Users;
using Holo.Source.GameConnectionSystem;
namespace Holo.Source.Socket_servers.Game_Socketsystem
{
public class messageHandler
{
// private virtualUser EndUser;
// private string LastReceivedPacket;
//private delegate void Packet();
// private Packet[] mPacket;
private gameConnection Connector;
}
}
GameSocketServer.cs Codice:
namespace Holo.Socketservers
{
using Holo;
using Holo.Virtual.Users;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using Holo.Managers;
using System.Collections;
using Ion.Storage;
using DOS.Storage;
using System.Threading;
using Holo.Source.GameConnectionSystem;
public static class gameSocketServer
{
private static Socket socketHandler;
private static int _Port = int.Parse(Config.getTableEntry("server_game_port"));
private static int _maxConnections = int.Parse(Config.getTableEntry("server_game_maxconnections"));
private static int _acceptedConnections;
private static HashSet<int> _activeConnections;
private static Hashtable connections = new Hashtable(2);
private static bool AcceptConnections = true;
private static int Connected;
#region Methods
private static void connectionRequest(IAsyncResult iAr)
{
try
{
int item = 0;
for (int i = 1; i < _maxConnections; i++)
{
if (!_activeConnections.Contains(i))
{
item = i;
break;
}
}
if (item > 0)
{
Socket connectionSocket = ((Socket)iAr.AsyncState).EndAccept(iAr);
Out.WriteLine(string.Concat(new object[] { "Accepted connection [", item, "] from ", connectionSocket.RemoteEndPoint.ToString().Split(new char[] { ':' })[0] }));
connectionHelper.Init();
_activeConnections.Add(item);
_acceptedConnections++;
new virtualUser(item, connectionSocket);
}
}
catch
{
}
socketHandler.BeginAccept(new AsyncCallback(gameSocketServer.connectionRequest), socketHandler);
}
internal static bool Init(int bindPort, int maxConnections)
{
_Port = bindPort;
_maxConnections = maxConnections;
_activeConnections = new HashSet<int>();
socketHandler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Out.WriteLine("Starting up asynchronous socket server for game connections for port " + bindPort + "...");
try
{
socketHandler.Bind(new IPEndPoint(IPAddress.Any, bindPort));
socketHandler.Listen(0x19);
socketHandler.BeginAccept(new AsyncCallback(gameSocketServer.connectionRequest), socketHandler);
Out.WriteLine("Asynchronous socket server for game connections running on port " + bindPort);
Out.WriteLine("Max simultaneous connections is " + maxConnections);
return true;
}
catch
{
Out.WriteError("Error while setting up asynchronous socket server for game connections on port " + bindPort);
Out.WriteError("Port " + bindPort + " could be invalid or in use already.");
return false;
}
}
internal static bool Int(int bindPort, int maxConnections)
{
_Port = bindPort;
_maxConnections = maxConnections;
_activeConnections = new HashSet<int>();
socketHandler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Out.WriteLine("Starting up asynchronous socket server for game connections for port " + bindPort + "...");
try
{
socketHandler.Bind(new IPEndPoint(IPAddress.Any, bindPort));
socketHandler.Listen(0x19);
socketHandler.BeginAccept(new AsyncCallback(gameSocketServer.connectionRequest), socketHandler);
Out.WriteLine("Asynchronous socket server for game connections running on port " + bindPort);
Out.WriteLine("Max simultaneous connections is " + maxConnections);
return true;
}
catch
{
Out.WriteError("Error while setting up asynchronous socket server for game connections on port " + bindPort);
Out.WriteError("Port " + bindPort + " could be invalid or in use already.");
return false;
}
}
internal static void Destroy()
{
AcceptConnections = false;
HashSet<int> Data = _activeConnections;
foreach (int ConnectionID in Data)
{
freeConnection(ConnectionID);
}
}
internal static void StartListening()
{
bool SomethingWentWrong = false;
try
{
if (_Port == 0 || _maxConnections == 0)
throw new NullReferenceException();
else
{
socketHandler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint Endpoint = new IPEndPoint(IPAddress.Any, _Port);
socketHandler.Bind(Endpoint);
socketHandler.Listen(1000);
while (!AcceptConnections)
{
socketHandler.BeginAccept(new AsyncCallback(InncommingDataRequest), socketHandler);
}
}
}
catch (Exception e)
{
Out.WriteError("Fatal error during socket setup:\r" + e.ToString());
SomethingWentWrong = true;
Holo.Eucalypt.Shutdown();
}
finally
{
if (!SomethingWentWrong)
{
socketHandler.BeginAccept(new AsyncCallback(InncommingDataRequest), socketHandler);
Out.WriteLine("Socket is ready");
}
}
}
internal static void InncommingDataRequest(IAsyncResult iAr)
{
// Out.WriteLine("New connectionRequest");
try
{
Socket ReplyFromComputer = ((Socket)iAr.AsyncState).EndAccept(iAr);
string IP = ReplyFromComputer.RemoteEndPoint.ToString().Split(':')[0];
int amount = GetConnectionAmount(IP);
if (acceptedConnections >= maxConnections || AcceptConnections == false)
{
ReplyFromComputer.Shutdown(SocketShutdown.Both);
ReplyFromComputer.Close();
}
else if (amount > 10)
{
ReplyFromComputer.Shutdown(SocketShutdown.Both);
ReplyFromComputer.Close();
connectionHelper.BanIP(IP);
}
else if (connectionHelper.IpIsBanned(IP) == true)
{
ReplyFromComputer.Shutdown(SocketShutdown.Both);
ReplyFromComputer.Close();
}
else
{
int ConnectionRequestID = NewConnectionRequestID();
if (ConnectionRequestID > 0)
{
Out.WriteLine("Accepted connection: [" + ConnectionRequestID + "] from [" + IP + "]");
AddConnection(IP);
new gameConnection(ReplyFromComputer, ConnectionRequestID);
//User.AddConect(, User);
//new virtualUser(ConnectionRequestID, ReplyFromComputer);
}
}
}
catch { }
socketHandler.BeginAccept(new AsyncCallback(InncommingDataRequest), socketHandler);
}
internal static int NewConnectionRequestID()
{
_acceptedConnections++;
_activeConnections.Add(_acceptedConnections);
return _acceptedConnections;
}
/// <summary>
/// Flags a connection as free.
/// </summary>
/// <param name="connectionID">The ID of the connection.</param>
internal static void freeConnection(int connectionID)
{
if (_activeConnections.Contains(connectionID))
{
_activeConnections.Remove(connectionID);
//Out.WriteLine("Flagged connection [" + connectionID + "] as free.");
_acceptedConnections--;
}
}
internal static void AddConnection(string IP)
{
int Amount = 0;
if (connections.ContainsKey(IP) == true)
{
Amount = (int)connections[IP];
connections.Remove(IP);
}
else
{
Amount = 0;
}
int newamount = Amount + 1;
connections.Add(IP, newamount);
}
internal static void RemoveConnection(string IP)
{
int IpConnected = 0;
if (connections.ContainsKey(IP) == true)
{
IpConnected = (int)connections[IP];
}
else
{
connections.Remove(IP);
}
if (IpConnected > 1) //More than one connected
{
int NewAmount = IpConnected - 1;
connections.Remove(IP);
connections.Add(IP, NewAmount);
}
else //Only one connected
{
connections.Remove(IP);
}
}
#endregion
#region Properities
internal static int GetConnectionAmount(string IP)
{
if (connections.ContainsKey(IP) == true)
{
return ((int)connections[IP]);
}
else
{
return 0;
}
}
internal static int maxConnections
{
/// <summary>
/// Gets or set an Integer for the maximum amount of connections at the same time.
/// </summary>
set
{
_maxConnections = value;
}
get
{
return _maxConnections;
}
}
internal static int acceptedConnections
{
/// <summary>
/// Returns as integer of the accepted connections count since init.
/// </summary>
get { return _acceptedConnections; }
}
#endregion
}
}
gameconnection.cs Codice:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Holo.Virtual.Users;
using Holo.Socketservers;
using Holo.Source.GameConnectionSystem;
using Holo.Source.Socket_servers.Game_Socketsystem;
using System.Threading;
namespace Holo.Source.GameConnectionSystem
{
public class gameConnection
{
#region Declares
private Socket ClientSocket;
private byte[] dataBuffer = new byte[1024];
private int _ConnectionID;
private virtualUser ConnectedUser;
private messageHandler Handler;
private bool SocketClosed = false;
private bool SocketReceivedPing = true;
private AsyncCallback Callback;
#endregion
#region Constructor
public gameConnection(Socket _ClientSocket, int _ConnectionID)
{
// this.Handler = new messageHandler(this);
// this.ConnectedUser = new virtualUser(this);
// Handler.SetUser(ConnectedUser);
//ConnectedUser.SetHandler(Handler);
this.ClientSocket = _ClientSocket;
this._ConnectionID = _ConnectionID;
ConnectedUser.pingOK = true;
Callback = new AsyncCallback(ReceivedData);
WaitForData();
Ping();
connectionHelper.AddConnection(this, _ConnectionID);
}
#endregion
#region Properities
internal string connectionRemoteIP
{
get
{
return ClientSocket.RemoteEndPoint.ToString().Split(':')[0];
}
}
internal messageHandler RemoteHandler
{
get
{
return Handler;
}
}
internal bool IsActive
{
get
{
try
{
return (bool)ClientSocket.Connected;
}
catch
{
return false;
}
}
}
internal int ConnectionID
{
get
{
return this._ConnectionID;
}
}
#endregion
#region Methods
private void WaitForData()
{
if (!SocketClosed)
{
try
{
ClientSocket.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, Callback, null);
}
catch
{
Close();
}
}
else
Close();
}
internal void Ping()
{
if (!ClientSocket.Connected)
Close();
else
sendData("@@");
}
private void ReceivedData(IAsyncResult iAr)
{
try
{
int bytesReceived = new int();
try
{
bytesReceived = ClientSocket.EndReceive(iAr);
}
catch
{
Close();
return;
}
StringBuilder DataBuffer = new StringBuilder();
DataBuffer.Append(System.Text.Encoding.Default.GetString(dataBuffer, 0, bytesReceived));
if (DataBuffer.ToString() == "" || DataBuffer.ToString().Contains("\x01") || DataBuffer.ToString().Contains("\x02") || DataBuffer.ToString().Contains("\x05") || DataBuffer.ToString().Contains("\x09"))
{
Close();
return;
}
while (DataBuffer.Length > 0)
{
int v = Encoding.decodeB64(DataBuffer.ToString().Substring(1, 2));
// Handler.ProcessPacket(DataBuffer.ToString().Substring(3, v));
DataBuffer.Remove(0, 3 + v);
}
}
finally
{
WaitForData();
}
}
internal void Close()
{
if (!SocketClosed)
{
SocketClosed = true;
try
{
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
gameSocketServer.freeConnection(_ConnectionID);
}
catch { }
// ConnectedUser.Reset();
connectionHelper.RemoveConnection(_ConnectionID);
Crash();
}
}
internal void sendData(string Data)
{
try
{
//Out.WriteSpecialLine(Data.Replace("\r", @"\r"), Out.logFlags.MehAction, ConsoleColor.White, ConsoleColor.DarkCyan, "> []", 2, ConsoleColor.Cyan);
byte[] dataBytes = System.Text.Encoding.Default.GetBytes(Data + Convert.ToChar(1));
ClientSocket.BeginSend(dataBytes, 0, dataBytes.Length, 0, new AsyncCallback(sentData), null);
}
catch
{
Close();
}
}
private void sentData(IAsyncResult iAr)
{
try { ClientSocket.EndSend(iAr); }
catch
{
Close();
}
}
internal void Pinged()
{
this.SocketReceivedPing = true;
}
private void Crash()
{
ClientSocket = null;
dataBuffer = null;
_ConnectionID = 0;
ConnectedUser = null;
Handler = null;
SocketClosed = true;
SocketReceivedPing = false;
Callback = null;
}
#endregion
}
}
quando lo compilo mi da i seguenti errori: Avviso:1 Il campo 'Holo.Source.Socket_servers.Game_Socketsystem.messageHandler.Connector' non è mai utilizzato C:\Users\***\Holo\Socketservers\Class1.cs 18 32 l'errore sarebbe questo: Codice:
private gameConnection Connector; Il campo 'Holo.Source.GameConnectionSystem.gameConnection.SocketReceivedPing' è assegnato, ma il relativo valore non è mai utilizzato C:\Users\***\Holo\Socketservers\gameconnection.cs 23 22 l'errore sarebbe questo: Codice:
private bool SocketReceivedPing = true; Avviso:3 Il campo 'Holo.Socketservers.gameSocketServer.Connected' non è mai utilizzato C:\***\Holo\Socketservers\gameSocketServer.cs 29 28 l'errore sarebbe questo: Codice:
private static int Connected; Ultima modifica di kulosia : 09-11-2010 alle 09:54. |
|
|
|
|
|
#2 |
|
Member
Iscritto dal: Jan 2010
Messaggi: 149
|
up please!
|
|
|
|
|
|
#3 |
|
Senior Member
Iscritto dal: Oct 2005
Messaggi: 3306
|
|
|
|
|
|
|
#4 |
|
Member
Iscritto dal: Jan 2010
Messaggi: 149
|
dovrei bannare alcuni ip su un server in c# quando usano DDoS.
in poche parole la mia domanda è come farlo? stò provando in questo modo ma ho risolto già un bel pò di errori ma questi non so risolverli. ora stò su un'altro pc come mi connetto sull'altro ti faccio sapere anche gli altri 2 errori tomminno. |
|
|
|
|
|
#5 | |
|
Senior Member
Iscritto dal: Oct 2005
Messaggi: 3306
|
Quote:
Altrimenti per un banale ban degli ip basta che tieni uno storico degli ip che si connettono con relativo timestamp, su un thread separato controlli questo elenco e se trovi ip che cercano ripetutamente di eseguire l'accesso li inserisci in una black list, che controllerai sul listen del server rifiutando la connessione agli ip presenti in questa lista. Ma questo non significa difendersi da attacchi DDoS in quanto non hai modo da codice di impedire che qualcuno si connetta al tuo server e quand'anche tu andassi a configurare il firewall della macchina per bloccare le connessioni provenienti da quel particolare ip, i pacchetti TCP continuano comunque ad intasare la tua scheda di rete. |
|
|
|
|
|
|
#6 | |
|
Senior Member
Iscritto dal: Mar 2009
Messaggi: 753
|
Quote:
Ad ognuno il suo compito insomma.... |
|
|
|
|
|
|
#7 |
|
Member
Iscritto dal: Jan 2010
Messaggi: 149
|
bhè che dire...
ho dovuto pagare ben 199$ per comprare un buon firewall chiamato fortguard ma che faccio ben poco per 2 motivi: 1. la porta del server il firewall lo blocca in ritardo 2. dura 1 anno ed in quest'anno vorrei fare qualcosa che non mi faccia spendere dinuovo 199$ bhè per quello che ha detto tomminno si mi servirebbe anche una cosa del genere per il server nel modo in cui stavo facendo non va bene? c'è qualche sorgente da qualche parte funzionante in modo da vedere come implementarlo nel server? per quello che ha detto Teo@Unix un firewall è comunque sempre un programma? come potre fare qualcosa del genere a me basta solo che blocchi gli ip ad un tot di connessioni che stò esplodendo non c'è la faccio più con questi DDoS mi sareste di grandissimo aiuto se riuscirò a fare qualcosa in modo da non pagare ogni anno 199$ Ultima modifica di kulosia : 14-11-2010 alle 02:54. |
|
|
|
|
|
#8 |
|
Member
Iscritto dal: Jul 2006
Messaggi: 109
|
Potresti vedere come fa RunUO ad esempio per firewallare: http://svn.runuo.com/RunUO-2.0-Final.zip
Devi guardare nella cartella Accounting, c'è sia la gestione del firewall per ip che imposti tu, sia per quando ci sono troppe connessioni consecutive. La parte automatica forse è un po' difficile da scorporare e riutilizzare ma da replicare è semplice... basta che ti tieni da qualche parte un Dictionary, ad esempio, con IP e corrispettivo numero di tentativi di connessione, che controlli nel ConnectionRequest in modo da accettare o meno la request. Chiaramente così carichi il server se sei sotto attacco e potresti avere rallentamenti per i login validi.. |
|
|
|
|
|
#9 | |
|
Senior Member
Iscritto dal: Oct 2005
Messaggi: 3306
|
Quote:
|
|
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 06:07.



















