Topics

Ban IP from logging in for 5 minutes after 10 failed logins


if( login_limit() )
   die( 'Your  has been banned from logging in  the next 5 minutes' );



/*
 * Counts login times by same  
 * returns true if limit reached or false if not 
 */
 login_limit(){
    //get real  if  behind proxy noted by Sebastian Enger
    $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
    
    // still banned from login
    if( _( $ip . 'banned' ) )
        return true;

    // of seconds 
    $sec = 30;
    //find ip info  in cache saved less than $sec ago
    if( ($ip_info=_cache( $ip ))  && $ip_info[0] > ()-$sec ){
        
        //user login 10 times during last $sec 
        if(  $ip_info[1] > 10 ){
            //ban user ip for the next 5 minutes
            _cache( $ip . 'banned', 1, 0, 60*5 );
            _cache( $ip, -1 );
            return true;
        }
        //increase login retries +1 
        _cache( $ip, array(  $ip_info[0],   ++$ip_info[1] ), 0, $sec );
        return false;
        
    }
        
    //add ip info to cache
    _cache( $ip, array( (), 1 ), 0, $sec );
    return false;
}

function _cache( $name, $val=NULL, $ttl=false ){
        //
	 $mcdb;
	if(empty($mcdb) ) 
		$mcdb = memcache_connect(':///etc/sockets/memcached.sock', 0);
	
	if($val === -1){
		return memcache_delete($mcdb,$name);
	}elseif( $val !== NULL ){
		return memcache_set($mcdb,$name,$val, false, $ttl);
	}else{
		$retval = memcache_get($mcdb,$name);
		return  $retval ? $retval : NULL;
	}

}