-1

I currently have a simple script that connects to the mysql. Each time a clients connects to that script i add +1 to the total max_connections inside the database for that IP.

In this script, I have a limit, for example

if($user['max_cons'] < 5)
{
    # ... do some things
}

However if a user floods this web script with many threads at once, he will be able to bypass it and open more than 5 connections. I tried it a python flooding script and it worked.

I guess it's because of the MySQL queries that needs some time to be imported into the database.

What I can do to prevent that?

(btw: I don't want to block the user even if he floods)

Thank you!

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
OhGodWhy
  • 165
  • 1
  • 11
  • Not sure there's much you can do code-wise for the actual connecting because you need to connect (and select) in order to check the max_connections value. – Shomz Jan 17 '15 at 13:03

3 Answers3

0

MySQL keeps a count of connections for you. Refer this answer to obtain that number.

Community
  • 1
  • 1
varun113
  • 451
  • 3
  • 11
  • And how i would know how many cons have been opened from a single IP? It's b ecause the max_connections limit is per ip. – OhGodWhy Jan 17 '15 at 13:09
0

If you are concerned about flooding or other forms of attacks, you need to act also in the infrastructure and networking layers of your system. Once the attack got to your code, you don't have much room to maneuver, as the application layer would have been already compromised.

Moreover, if you design your defense this way, you would need to repeat or include this code in every other piece of code you program. Acting on the infrastructure and/or networking layers will give you the chance to add security and protection as a cross-cutting concern or an "aspect" of your system, adding it once and intercepting all requests.

Your code checking 'max_conns' for each user seems more like a quota check to me, a feature of your website if you will. You could use that to prevent a user accidentally using more connections than you want to allow, but if you want to defend against actual intended attacks, you need to do some research on infrastructure and networking security, as it's a very broad subject.

Two more notes:

  • Maybe your hosting provider already provides some sort of defense against this and you could rely on that? Or are you hosting it yourself?
  • Maybe take this to superuser.com?
jotadepicas
  • 2,389
  • 2
  • 26
  • 48
0

You can use

sleep(1);//sleep for one second

just before checking number of connections, but after you've increased number of connections for the ip. Something like

   increaseConnectionsCount($user);//but max_cons should be affected n this method
   sleep(1);
   $user = reloadUser();
   if($user['max_cons'] < 5) {
     ...
maxpovver
  • 1,580
  • 14
  • 25