Перейти к контенту

Капча на авторизацию - защита от брута


Рекомендуемые сообщения

Вот держите мод

 

IPB AntiBruteForce v1.0

 

(IM) Login Captcha.rar

 

Установка:

 

IPB 2.3.6 AntiBruteForce v1.0 by Babka http://fpteam-cheats.com

 

Made from mod loginCaptcha by Martin Aronsen

 

Mod installation

 

Upload folder "upload"

 

Log in to your Admin CP and go to the Components tab -> (FSY22) Universal Mod Installer -> Manage Mod Installations page. Look for the entry for this mod, click the grey Options button beside it, and click the Install link. The installer script will read the mod's XML file and determine the proper installation steps, then you can click the Proceed button to have it execute these actions.

 

 

 

 

File Edits

Open: ./sources/action_public/login.php

 

 

Находим/Search

=========================================================================================================================================

case 'autologin':

$this->auto_login();

break;

 

=========================================================================================================================================

Добавляем ниже/Add after

=========================================================================================================================================

/* AntiBruteForce Start */

case 'aftercaptcha':

$this->afterCaptcha();

break;

/* AntiBruteForce End */

=========================================================================================================================================

 

 

 

 

 

 

 

 

Находим/Search

=========================================================================================================================================

/*

I see no reason to limit how long the password can be...

 

if ( $this->ipsclass->txt_mb_strlen( $_POST['PassWord'] ) > 32)

{

$this->ipsclass->Error( array( LEVEL => 1, MSG => 'pass_too_long' ) );

}*/

 

$password = md5( $this->ipsclass->input['PassWord'] );

 

=========================================================================================================================================

Добавляем ниже/Add after

=========================================================================================================================================

/* AntiBruteForce Start */

if ( $this->ipsclass->vars['abf_loginCaptcha-enabled'] )

{

 

$member['username'] = $username;

$member['password'] = $this->ipsclass->input['PassWord'];

 

 

$this->solveCaptcha( $member );

 

}

/* AntiBruteForce End */

=========================================================================================================================================

 

 

 

 

 

 

 

 

 

 

 

 

Находим/Search

=========================================================================================================================================

}

 

?>

=========================================================================================================================================

Добавляем ВЫШЕ/Add BEFORE

=========================================================================================================================================

 

/* AntiBruteForce Start */

 

function solveCaptcha( $member, $error="" )

{

// Have any errors?

if ( $error != "" )

{

$message = $this->ipsclass->lang[ $error ];

 

$this->output .= $this->ipsclass->compiled_templates['skin_login']->errors($message);

}

 

 

$this->output .= $this->ipsclass->compiled_templates['skin_login']->loginCaptcha( $member );

 

// Grab CAPTCHA template bit

require_once( KERNEL_PATH . 'class_captcha.php' );

$captchaClass = new class_captcha( $this->ipsclass, $this->ipsclass->vars['bot_antispam_type'] );

$captchaHTML = $captchaClass->getTemplate();

 

$this->output = str_replace( "<!--{REG.ANTISPAM}-->", $captchaHTML, $this->output );

 

$this->nav = array( $this->ipsclass->lang['log_in'] );

$this->page_title = $this->ipsclass->lang['log_in'];

 

$this->ipsclass->print->add_output( $this->output );

$this->ipsclass->print->do_output( array( 'TITLE' => $this->page_title, 'JS' => 0, 'NAV' => $this->nav, 'OVERRIDE' => $this->ipsclass->vars['board_offline'] ) );

 

exit();

}

 

/**

* ABF Login Captcha

*

* Check if the captcha is correct, and log the member in

*

* @return void

*/

function afterCaptcha()

{

 

 

if ( $this->ipsclass->vars['abf_loginCaptcha-enabled'] )

{

// Validate CAPTCHA

require_once( KERNEL_PATH . 'class_captcha.php' );

$captchaClass = new class_captcha( $this->ipsclass, $this->ipsclass->vars['bot_antispam_type'] );

 

if ( $captchaClass->validate() !== TRUE )

{

$username = strtolower( trim( $this->ipsclass->input['username'] ) );

$member['username'] = $username;

$member['password'] = $this->ipsclass->input['password'];

 

$this->solveCaptcha( $member, 'err_reg_code');

}

}

 

 

require_once( ROOT_PATH.'sources/handlers/han_login.php' );

$this->han_login = new han_login();

$this->han_login->ipsclass =& $this->ipsclass;

$this->han_login->init();

 

//-----------------------------------------

// Make sure the username and password were entered

//-----------------------------------------

 

if ( $_POST['username'] == "" )

{

if( $this->ipsclass->vars['ipbli_usertype'] == 'username' )

{

$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_username' ) );

}

else

{

$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_email_login' ) );

}

}

 

if ( $_POST['password'] == "" )

{

$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'pass_blank' ) );

}

 

//-----------------------------------------

// Check for input length

//-----------------------------------------

 

if ( $this->ipsclass->vars['ipbli_usertype'] == 'username' )

{

if ( $this->ipsclass->txt_mb_strlen( $_POST['username'] ) > 32 )

{

$this->ipsclass->Error( array( LEVEL => 1, MSG => 'username_long' ) );

}

 

$username = strtolower(str_replace( '|', '|', $this->ipsclass->input['username']) );

}

else

{

$username = strtolower( trim( $this->ipsclass->input['username'] ) );

}

 

 

 

//-----------------------------------------

// Check auth

//-----------------------------------------

 

$this->han_login->login_authenticate( $username, $this->ipsclass->input['password'] );

 

//-----------------------------------------

// Check return code...

//-----------------------------------------

 

$member = $this->han_login->member;

 

if ( ( ! $member['id'] ) or ( $this->han_login->return_code == 'NO_USER' ) )

{

$this->log_in_form( 'wrong_name' );

}

 

if ( $this->han_login->return_code != 'SUCCESS' )

{

if ( $this->han_login->return_code == 'ACCOUNT_LOCKED' )

{

$extra = "<!-- -->";

 

if( $this->ipsclass->vars['ipb_bruteforce_unlock'] )

{

if( $this->han_login->account_unlock )

{

$time = time() - $this->han_login->account_unlock;

 

$time = ( $this->ipsclass->vars['ipb_bruteforce_period'] - ceil( $time / 60 ) > 0 ) ? $this->ipsclass->vars['ipb_bruteforce_period'] - ceil( $time / 60 ) : 1;

 

$extra = sprintf( $this->ipsclass->lang['bruteforce_account_unlock'], $time );

}

}

 

$this->ipsclass->Error( array( 'LEVEL' => 5, 'MSG' => 'bruteforce_account_lock', 'EXTRA' => $extra ) );

}

else

{

 

$this->log_in_form( 'wrong_auth' );

 

}

}

 

 

 

 

 

 

 

 

 

 

 

if ( $member['members_created_remote'] )

{

$pmember = $this->ipsclass->DB->build_and_exec_query( array( 'select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id={$member['id']}" ) );

 

if ( $pmember['partial_member_id'] )

{

$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['partial_login'], 'act=reg&CODE=complete_login&mid='.$member['id'].'&key='.$pmember['partial_date'] );

exit();

}

}

 

//-----------------------------------------

// Generate a new log in key

//-----------------------------------------

 

$_ok = 1;

$_time = ( $this->ipsclass->vars['login_key_expire'] ) ? ( time() + ( intval($this->ipsclass->vars['login_key_expire']) * 86400 ) ) : 0;

$_sticky = $_time ? 0 : 1;

$_days = $_time ? $this->ipsclass->vars['login_key_expire'] : 365;

 

if ( $this->ipsclass->vars['login_change_key'] OR ! $member['member_login_key'] OR ( $this->ipsclass->vars['login_key_expire'] AND ( time() > $member['member_login_key_expire'] ) ) )

{

$member['member_login_key'] = $this->ipsclass->converge->generate_auto_log_in_key();

 

$this->ipsclass->DB->do_update( 'members', array( 'member_login_key' => $member['member_login_key'],

'member_login_key_expire' => $_time ), 'id='.$member['id'] );

}

 

//-----------------------------------------

// Strong hold cookie?

//-----------------------------------------

 

$this->ipsclass->stronghold_set_cookie( $member['id'], $member['member_login_key'], 1 );

 

//-----------------------------------------

// Cookie me softly?

//-----------------------------------------

 

 

 

if ( $this->ipsclass->input['CookieDate'] )

{

$this->ipsclass->my_setcookie("member_id" , $member['id'] , 1 );

$this->ipsclass->my_setcookie("pass_hash" , $member['member_login_key'], $_sticky, $_days );

}

 

//-----------------------------------------

// Remove any COPPA cookies previously set

//-----------------------------------------

 

$this->ipsclass->my_setcookie("coppa", '0', 0);

 

//-----------------------------------------

// Update profile if IP addr missing

//-----------------------------------------

 

if ( $member['ip_address'] == "" OR $member['ip_address'] == '127.0.0.1' )

{

$this->ipsclass->DB->simple_construct( array( 'update' => 'members',

'set' => "ip_address='{$this->ipsclass->ip_address}'",

'where' => "id={$member['id']}"

) );

 

$this->ipsclass->DB->simple_exec();

}

 

//-----------------------------------------

// Create / Update session

//-----------------------------------------

 

$poss_session_id = "";

 

if ( $cookie_id = $this->ipsclass->my_getcookie('session_id') )

{

$poss_session_id = $this->ipsclass->my_getcookie('session_id');

}

else if ( $this->ipsclass->input['s'] )

{

$poss_session_id = $this->ipsclass->input['s'];

}

 

//-----------------------------------------

// Clean...

//-----------------------------------------

 

$poss_session_id = preg_replace("/([^a-zA-Z0-9])/", "", $poss_session_id);

 

if ( $poss_session_id )

{

$session_id = $poss_session_id;

 

if( $this->ipsclass->vars['match_ipaddress'] )

{

//-----------------------------------------

// Delete any old sessions with this users IP

// addy that doesn't match our session ID.

//-----------------------------------------

 

$this->ipsclass->DB->simple_construct( array( 'delete' => 'sessions',

'where' => "ip_address='".$this->ipsclass->ip_address."' AND id <> '$session_id'"

) );

 

$this->ipsclass->DB->simple_shutdown_exec();

}

 

if( $this->ipsclass->vars['disable_anonymous'] )

{

$privacy = 0;

}

else

{

$privacy = ( isset($this->ipsclass->input['Privacy']) AND $this->ipsclass->input['Privacy']) ? 1 : 0;

}

 

$this->ipsclass->DB->do_shutdown_update( 'sessions',

array (

'member_name' => $member['members_display_name'],

'member_id' => $member['id'],

'running_time' => time(),

'member_group' => $member['mgroup'],

'login_type' => $privacy

),

"id='".$session_id."'"

);

}

else

{

$session_id = md5( uniqid(microtime()) );

 

if( $this->ipsclass->vars['disable_anonymous'] )

{

$privacy = 0;

}

else

{

$privacy = $this->ipsclass->input['Privacy'] ? 1 : 0;

}

 

if( $this->ipsclass->vars['match_ipaddress'] )

{

//-----------------------------------------

// Delete any old sessions with this users IP addy.

//-----------------------------------------

 

$this->ipsclass->DB->simple_construct( array( 'delete' => 'sessions',

'where' => "ip_address='".$this->ipsclass->ip_address."'"

) );

 

$this->ipsclass->DB->simple_shutdown_exec();

}

 

$this->ipsclass->DB->do_shutdown_insert( 'sessions',

array (

'id' => $session_id,

'member_name' => $member['members_display_name'],

'member_id' => $member['id'],

'running_time' => time(),

'member_group' => $member['mgroup'],

'ip_address' => $this->ipsclass->ip_address,

'browser' => substr($this->ipsclass->clean_value($this->ipsclass->my_getenv('HTTP_USER_AGENT')), 0, 50),

'login_type' => $privacy

) );

}

 

 

$this->ipsclass->member = $member;

$this->ipsclass->session_id = $session_id;

 

if (isset($this->ipsclass->input['referer']) AND $this->ipsclass->input['referer'] && ($this->ipsclass->input['act'] != 'Reg'))

{

$url = str_replace( '&', '&', $this->ipsclass->input['referer'] );

$url = str_replace( "{$this->ipsclass->vars['board_url']}/index.{$this->ipsclass->vars['php_ext']}", "", $url );

$url = preg_replace( "!^\?!" , "" , $url );

$url = preg_replace( "!s=(\w){32}!", "" , $url );

$url = preg_replace( "!act=(login|reg|lostpass)!i", "", $url );

}

 

//-----------------------------------------

// Set our privacy status

//-----------------------------------------

 

$this->ipsclass->DB->simple_construct( array( 'update' => 'members',

'set' => "login_anonymous='".intval($privacy)."&1', failed_logins='', failed_login_count=0",

'where' => "id={$member['id']}"

) );

 

$this->ipsclass->DB->simple_shutdown_exec();

 

//-----------------------------------------

// Clear out any passy change stuff

//-----------------------------------------

 

$this->ipsclass->DB->simple_construct( array( 'delete' => 'validating',

'where' => "member_id={$this->ipsclass->member['id']} AND lost_pass=1"

) );

 

$this->ipsclass->DB->simple_shutdown_exec();

 

//-----------------------------------------

// Redirect them to either the board

// index, or where they came from

//-----------------------------------------

 

$this->ipsclass->my_setcookie("session_id", $this->ipsclass->session_id, -1);

 

$this->logged_in = 1;

 

if ( USE_MODULES == 1 )

{

$this->modules->register_class($this);

$this->modules->on_login($member);

}

 

if ( isset($this->ipsclass->input['return']) AND $this->ipsclass->input['return'] != "" )

{

$return = urldecode($this->ipsclass->input['return']);

 

if ( preg_match( "#^http://#", $return ) )

{

$this->ipsclass->boink_it($return);

}

}

 

//-----------------------------------------

// Check for dupemail

//-----------------------------------------

 

$member_extra = $this->ipsclass->DB->simple_exec_query( array( 'select' => 'bio', 'from' => 'member_extra', 'where' => 'id='.$member['id'] ) );

 

if ( $member_extra['bio'] == 'dupemail' )

{

$this->ipsclass->print->redirect_screen( "{$this->ipsclass->lang['thanks_for_login']} {$this->ipsclass->member['members_display_name']}", 'act=usercp&CODE=00' );

}

else

{

$this->ipsclass->print->redirect_screen( "{$this->ipsclass->lang['thanks_for_login']} {$this->ipsclass->member['members_display_name']}", $url );

}

}

 

/* AntiBruteForce End */

 

 

 

=========================================================================================================================================

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

У меня общая защита от ботов; ей все равно, брут или парсер контента, если критерии соотвтетствуют, в бан через эйчтиакцесс. Изменено пользователем FatCat
Ссылка на комментарий
Поделиться на других сайтах

У меня общая защита от ботов; ей все равно, брут или парсер контента, если критерии соотвтетствуют, в бан через эйчтиакцесс.

 

Отлично, от брута без подключения проксей вы защищены.

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

а собственно что происходит с помощью этого мода и защищает ли он от брута с подключением прокси?

как я понял, он просто не дает войти, отправляет на вход заново, и никак не запиливает нарушителя вообще

Ссылка на комментарий
Поделиться на других сайтах

Защита от брута заключается в том что невозможно настроить брут на определение положительного результата (и отрицательного). Если проверяется рабочая пара логин-пас брут не может авторизоваться без подключения какой-либо антикапчи. Но брутить с антикапчей дорого.

 

 

20$ за переделку плагина пока сам пытаюсь . Но только если мне поставится. Особенность сайта - login.php авторизует также и на DLE, т.е. стоит перемычка между движками от калиостро.

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

возможно) нет авторизации - нет надписи "Вы вошли как:"

 

ну а вообще лучшая защита от брута - мод, проверяющий стойкость пароля при регистрации, где-то видел такой

Ссылка на комментарий
Поделиться на других сайтах

Пароль уже самостоятельно переписал, до этого был просто ужас: пропускало от 3 символом и можно было что бы логин = пароль.

 

Но даже сейчас моя проверка не пропустит

qwerty

123456

 

но пропустит

qwerty1

и еще огромное количество.

Наверное все-таки добавлю вскоре требование минимум 1 буквы верхнего регистра в пароле. Но это не устраняет уже установленные пароли. Нужен мод чтоб требовал смену пароля по прошествии определенного периода.

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

ну а переделать легко очень

                        $mem = $this->ipsclass->DB->build_and_exec_query( array( 'select' => 'posts', 'from' => 'members', 'where' => 'id=' . $member['id'] ) );

                       $member = array_merge( $member, $mem );

                       $this->ipsclass->vars['im_loginCaptcha-minPosts'] = intval( $this->ipsclass->vars['im_loginCaptcha-minPosts'] ) ? $this->ipsclass->vars['im_loginCaptcha-minPosts'] : 5;

                       if ( $member['posts'] <= $this->ipsclass->vars['im_loginCaptcha-minPosts'] )

 

вот эту бадягу отовсюду просто выкинуть

будет срабатывать всегда, ибо

if ( $member['posts'] <= $this->ipsclass->vars['im_loginCaptcha-minPosts'] )

уже не будет проверяться

да и минус лишний запрос к бд

 

останутся только такие настройки,как enable и защищенные группы

ну и в skin_login->loginCaptcha или в

$this->ipsclass->lang['login_captcha'] = sprintf( $this->ipsclass->lang['login_captcha'], $this->ipsclass->vars['im_loginCaptcha-minPosts'] );

и соотв. языке изменения сделать

Ссылка на комментарий
Поделиться на других сайтах

СТЕРТО

 

Убрал проверку постов и возможность ставить группы которые обходят капчу.

 

Тут похитрее чуть чуть, тут надо чтобы о неверной авторизации пользователю сообщалось только после _правильного_ ввода капчи

 

 

update

в коде выше ошибка: при неправильной вводе капчи защитывается + 1 неправильная авторизация, соответственно 5 раз неправильно ввел капчу - блокируется логин. Я это уже исправил но лучше я хорошенько потестю код на своем форуме а позже уже выложу окончательно

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

Итак вроде пока работает. Установка мода антибрута производится так:

качаем мод логин капча

http://forums.ibresource.ru/index.php?app=core&module=attach&section=attach&attach_id=4386

Устанавлимаем, но в файл

./sources/action_public/login.php

Вносим не как там изменения, а те, что ниже:

 

Находим

case 'autologin':
               $this->auto_login();
               break;

Вставляем ниже

case 'aftercaptcha':
               $this->afterCaptcha();
               break;

 

Находим

if ( $this->han_login->return_code != 'SUCCESS' )
       {
           if ( $this->han_login->return_code == 'ACCOUNT_LOCKED' )
           {
               $extra = "<!-- -->";

               if( $this->ipsclass->vars['ipb_bruteforce_unlock'] )
               {
                   if( $this->han_login->account_unlock )
                   {
                       $time = time() - $this->han_login->account_unlock;

                       $time = ( $this->ipsclass->vars['ipb_bruteforce_period'] - ceil( $time / 60 ) > 0 ) ? $this->ipsclass->vars['ipb_bruteforce_period'] - ceil( $time / 60 ) : 1;

                       $extra = sprintf( $this->ipsclass->lang['bruteforce_account_unlock'], $time );
                   }
               }

               $this->ipsclass->Error( array( 'LEVEL' => 5, 'MSG' => 'bruteforce_account_lock', 'EXTRA' => $extra ) );
           }
           else
           {

Вставляем ниже

if ( $this->ipsclass->vars['im_loginCaptcha-enabled']	)
			{

			$member['username'] = $username;
			$member['password'] = $this->ipsclass->input['PassWord'];

			$this->solveCaptcha( $member );

			}

			else 
			{

 

 

 

Находим (буквально следующая строчка)

$this->log_in_form( 'wrong_auth' );

Вставляем ниже


}		

 

 

 

Находим

   //-----------------------------------------
       // Is this a partial member?
       // Not completed their sign in?
       //-----------------------------------------

Вставляем ВЫШЕ

                if ( $this->ipsclass->vars['im_loginCaptcha-enabled']    )
               {

               $member['username'] = $username;
               $member['password'] = $this->ipsclass->input['PassWord'];

               $this->solveCaptcha( $member);

               }

 

 

 

Находим

}

?>

Вставляем ВЫШЕ

    /**
    * (IM) Login Captcha
    *
    * Serve a captcha puzzle if the member has less than X posts
    *
    * @param     array        Member array
    * @return    void
    */
   function solveCaptcha( $member, $error="" )
   {
       // Have any errors?
       if ( $error != "" )
       {
           $message = $this->ipsclass->lang[ $error ];

           $this->output .= $this->ipsclass->compiled_templates['skin_login']->errors($message);
       }

       $this->ipsclass->lang['login_captcha'] = sprintf( $this->ipsclass->lang['login_captcha'], $this->ipsclass->vars['im_loginCaptcha-minPosts'] );

       $this->output .= $this->ipsclass->compiled_templates['skin_login']->loginCaptcha( $member );

       // Grab CAPTCHA template bit
       require_once( KERNEL_PATH . 'class_captcha.php' );
       $captchaClass = new class_captcha( $this->ipsclass, $this->ipsclass->vars['bot_antispam_type'] );
       $captchaHTML  = $captchaClass->getTemplate();

       $this->output = str_replace( "<!--{REG.ANTISPAM}-->", $captchaHTML, $this->output );

       $this->nav        = array( $this->ipsclass->lang['log_in'] );
        $this->page_title = $this->ipsclass->lang['log_in'];

       $this->ipsclass->print->add_output( $this->output );
       $this->ipsclass->print->do_output( array( 'TITLE' => $this->page_title, 'JS' => 0, 'NAV' => $this->nav, 'OVERRIDE' => $this->ipsclass->vars['board_offline'] ) );

       exit();
   }

   /**
    * (IM) Login Captcha 
    *
    * Check if the captcha is correct, and log the member in
    *
    * @return    void
    */
   function afterCaptcha()
   {
       require_once( ROOT_PATH.'sources/handlers/han_login.php' );
       $this->han_login           =  new han_login();
       $this->han_login->ipsclass =& $this->ipsclass;
       $this->han_login->init();

       //-----------------------------------------
       // Make sure the username and password were entered
       //-----------------------------------------

       if ( $_POST['username'] == "" )
       {
           if( $this->ipsclass->vars['ipbli_usertype'] == 'username' )
           {
               $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_username' ) );
           }
           else
           {
               $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_email_login' ) );
           }
       }

        if ( $_POST['password'] == "" )
        {
           $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'pass_blank' ) );
       }   

       //-----------------------------------------
       // Check for input length
       //-----------------------------------------

       if ( $this->ipsclass->vars['ipbli_usertype'] == 'username' )
       {
           if ( $this->ipsclass->txt_mb_strlen( $_POST['username'] ) > 32 )
           {
               $this->ipsclass->Error( array( LEVEL => 1, MSG => 'username_long' ) );
           }

           $username = strtolower(str_replace( '|', '|', $this->ipsclass->input['username']) );
       }
       else
       {
           $username = strtolower( trim( $this->ipsclass->input['username'] ) );
       }


       if ( $this->ipsclass->vars['im_loginCaptcha-enabled'] )
       {
           // Validate CAPTCHA
           require_once( KERNEL_PATH . 'class_captcha.php' );
           $captchaClass = new class_captcha( $this->ipsclass, $this->ipsclass->vars['bot_antispam_type'] );

           if ( $captchaClass->validate() !== TRUE )
           {
               $member['username'] = $username;
               $member['password'] = $this->ipsclass->input['password'];

               $this->solveCaptcha( $member, 'err_reg_code');
           }
       }


       //-----------------------------------------
       // Check auth
       //-----------------------------------------

       $this->han_login->login_authenticate( $username, $this->ipsclass->input['password'] );

       //-----------------------------------------
       // Check return code...
       //-----------------------------------------

       $member = $this->han_login->member;


           if ( ( ! $member['id'] ) or ( $this->han_login->return_code == 'NO_USER' ) )
       {
           $this->log_in_form( 'wrong_name' );
       }

       if ( $this->han_login->return_code != 'SUCCESS' )
       {
               //    $netapara = 1;
                   $this->log_in_form( 'wrong_auth' );

       }






       // if ($netapara ) { $this->log_in_form( 'wrong_auth' ); }


       if ( $member['members_created_remote'] )
       {
           $pmember = $this->ipsclass->DB->build_and_exec_query( array( 'select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id={$member['id']}" ) );

           if ( $pmember['partial_member_id'] )
           {
               $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['partial_login'], 'act=reg&CODE=complete_login&mid='.$member['id'].'&key='.$pmember['partial_date'] );
               exit();
           }
       }

       //-----------------------------------------
       // Generate a new log in key
       //-----------------------------------------

       $_ok     = 1;
       $_time   = ( $this->ipsclass->vars['login_key_expire'] ) ? ( time() + ( intval($this->ipsclass->vars['login_key_expire']) * 86400 ) ) : 0;
       $_sticky = $_time ? 0 : 1;
       $_days   = $_time ? $this->ipsclass->vars['login_key_expire'] : 365;

       if ( $this->ipsclass->vars['login_change_key'] OR ! $member['member_login_key'] OR ( $this->ipsclass->vars['login_key_expire'] AND ( time() > $member['member_login_key_expire'] ) ) )
       {
           $member['member_login_key'] = $this->ipsclass->converge->generate_auto_log_in_key();

           $this->ipsclass->DB->do_update( 'members', array( 'member_login_key'         => $member['member_login_key'],
                                                              'member_login_key_expire' => $_time ), 'id='.$member['id'] );
       }

       //-----------------------------------------
       // Strong hold cookie?
       //-----------------------------------------

       $this->ipsclass->stronghold_set_cookie( $member['id'], $member['member_login_key'], 1 );

       //-----------------------------------------
       // Cookie me softly?
       //-----------------------------------------

       if ( $this->ipsclass->input['CookieDate'] )
       {
           $this->ipsclass->my_setcookie("member_id"   , $member['id']              , 1 );
           $this->ipsclass->my_setcookie("pass_hash"   , $member['member_login_key'], $_sticky, $_days );
       }

       //-----------------------------------------
       // Remove any COPPA cookies previously set
       //-----------------------------------------

       $this->ipsclass->my_setcookie("coppa", '0', 0);

       //-----------------------------------------
       // Update profile if IP addr missing
       //-----------------------------------------

       if ( $member['ip_address'] == "" OR $member['ip_address'] == '127.0.0.1' )
       {
           $this->ipsclass->DB->simple_construct( array( 'update' => 'members',
                                                         'set'    => "ip_address='{$this->ipsclass->ip_address}'",
                                                         'where'  => "id={$member['id']}"
                                                )      );

           $this->ipsclass->DB->simple_exec();
       }

       //-----------------------------------------
       // Create / Update session
       //-----------------------------------------

       $poss_session_id = "";

       if ( $cookie_id = $this->ipsclass->my_getcookie('session_id') )
       {
           $poss_session_id = $this->ipsclass->my_getcookie('session_id');
       }
       else if ( $this->ipsclass->input['s'] )
       {
           $poss_session_id = $this->ipsclass->input['s'];
       }

       //-----------------------------------------
       // Clean...
       //-----------------------------------------

       $poss_session_id = preg_replace("/([^a-zA-Z0-9])/", "", $poss_session_id);

       if ( $poss_session_id )
       {
           $session_id = $poss_session_id;

           if( $this->ipsclass->vars['match_ipaddress'] )
           {
               //-----------------------------------------
               // Delete any old sessions with this users IP
               // addy that doesn't match our session ID.
               //-----------------------------------------

               $this->ipsclass->DB->simple_construct( array( 'delete' => 'sessions',
                                                             'where'  => "ip_address='".$this->ipsclass->ip_address."' AND id <> '$session_id'"
                                                    )      );

               $this->ipsclass->DB->simple_shutdown_exec();
           }

           if( $this->ipsclass->vars['disable_anonymous'] )
           {
               $privacy = 0;
           }
           else
           {
               $privacy = ( isset($this->ipsclass->input['Privacy']) AND $this->ipsclass->input['Privacy']) ? 1 : 0;
           }

           $this->ipsclass->DB->do_shutdown_update( 'sessions',
                                                    array (
                                                            'member_name'  => $member['members_display_name'],
                                                            'member_id'    => $member['id'],
                                                            'running_time' => time(),
                                                            'member_group' => $member['mgroup'],
                                                            'login_type'   => $privacy
                                                          ),
                                                    "id='".$session_id."'"
                                                );
       }
       else
       {
           $session_id = md5( uniqid(microtime()) );

           if( $this->ipsclass->vars['disable_anonymous'] )
           {
               $privacy = 0;
           }
           else
           {
               $privacy = $this->ipsclass->input['Privacy'] ? 1 : 0;
           }            

           if( $this->ipsclass->vars['match_ipaddress'] )
           {
               //-----------------------------------------
               // Delete any old sessions with this users IP addy.
               //-----------------------------------------

               $this->ipsclass->DB->simple_construct( array( 'delete' => 'sessions',
                                                             'where'  => "ip_address='".$this->ipsclass->ip_address."'"
                                                    )      );

               $this->ipsclass->DB->simple_shutdown_exec();
           }

           $this->ipsclass->DB->do_shutdown_insert( 'sessions',
                                                    array (
                                                            'id'           => $session_id,
                                                            'member_name'  => $member['members_display_name'],
                                                            'member_id'    => $member['id'],
                                                            'running_time' => time(),
                                                            'member_group' => $member['mgroup'],
                                                            'ip_address'   => $this->ipsclass->ip_address,
                                                            'browser'      => substr($this->ipsclass->clean_value($this->ipsclass->my_getenv('HTTP_USER_AGENT')), 0, 50),
                                                            'login_type'   => $privacy
                                                 )       );
       }


       $this->ipsclass->member           = $member;
       $this->ipsclass->session_id       = $session_id;

       if (isset($this->ipsclass->input['referer']) AND $this->ipsclass->input['referer'] && ($this->ipsclass->input['act'] != 'Reg'))
       {
           $url = str_replace( '&', '&', $this->ipsclass->input['referer'] );
           $url = str_replace( "{$this->ipsclass->vars['board_url']}/index.{$this->ipsclass->vars['php_ext']}", "", $url );
           $url = preg_replace( "!^\?!"       , ""   , $url );
           $url = preg_replace( "!s=(\w){32}!", ""   , $url );
           $url = preg_replace( "!act=(login|reg|lostpass)!i", "", $url );
       }

       //-----------------------------------------
       // Set our privacy status
       //-----------------------------------------

       $this->ipsclass->DB->simple_construct( array( 'update' => 'members',
                                                     'set'    => "login_anonymous='".intval($privacy)."&1', failed_logins='', failed_login_count=0",
                                                     'where'  => "id={$member['id']}"
                                            )      );

       $this->ipsclass->DB->simple_shutdown_exec();

       //-----------------------------------------
       // Clear out any passy change stuff
       //-----------------------------------------

       $this->ipsclass->DB->simple_construct( array( 'delete' => 'validating',
                                                     'where'  => "member_id={$this->ipsclass->member['id']} AND lost_pass=1"
                                            )      );

       $this->ipsclass->DB->simple_shutdown_exec();

       //-----------------------------------------
       // Redirect them to either the board
       // index, or where they came from
       //-----------------------------------------

       $this->ipsclass->my_setcookie("session_id", $this->ipsclass->session_id, -1);

       $this->logged_in = 1;

       if ( USE_MODULES == 1 )
       {
           $this->modules->register_class($this);
           $this->modules->on_login($member);
       }

       if ( isset($this->ipsclass->input['return']) AND $this->ipsclass->input['return'] != "" )
       {
           $return = urldecode($this->ipsclass->input['return']);

           if ( preg_match( "#^http://#", $return ) )
           {
               $this->ipsclass->boink_it($return);
           }
       }

       //-----------------------------------------
       // Check for dupemail
       //-----------------------------------------

       $member_extra = $this->ipsclass->DB->simple_exec_query( array( 'select' => 'bio', 'from' => 'member_extra', 'where' => 'id='.$member['id'] ) );

       if ( $member_extra['bio'] == 'dupemail' )
       {
           $this->ipsclass->print->redirect_screen( "{$this->ipsclass->lang['thanks_for_login']} {$this->ipsclass->member['members_display_name']}", 'act=usercp&CODE=00' );
       }
       else
       {
           $this->ipsclass->print->redirect_screen( "{$this->ipsclass->lang['thanks_for_login']} {$this->ipsclass->member['members_display_name']}", $url );
       }
   }

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

Такая проблема: если выключить мод ( в админке в настройке ) то все ок, а при работающем происходит следующее:

 

Если авторизоваться то все окей, но стоит закрыть браузер (мозилла или ие) и открыть снова и зайти на сайт - авторизация сброшена. Куки в браузере не стираются, но в акк не заходит. Т.е. авторизация живет пока работает браузер, стоит перезапустить - все, авторизация слетела.

 

В чем может быть проблема?

Ссылка на комментарий
Поделиться на других сайтах

Такая проблема: если выключить мод ( в админке в настройке ) то все ок, а при работающем происходит следующее:

 

Если авторизоваться то все окей, но стоит закрыть браузер (мозилла или ие) и открыть снова и зайти на сайт - авторизация сброшена. Куки в браузере не стираются, но в акк не заходит. Т.е. авторизация живет пока работает браузер, стоит перезапустить - все, авторизация слетела.

 

В чем может быть проблема?

проверяйте, почему не происходит авторизация по кукам, скорее всего там добавлен еще один параметр, связанный с капчей, он и проверяется.

Ссылка на комментарий
Поделиться на других сайтах

Да, спасибо. Тоже вчера подумал надо смотреть куки. Сейчас проанализировал и вычислил что если авторизация идет по пути проверки капчи, то кука "member_id", которая до авторизации равна нулю, после авторизации тоже остается нулем и не меняется на id юзера.

 

Вычислил что в файле login.php после того как прошла проверка на капчу идет код

 

        //-----------------------------------------
       // Strong hold cookie?
       //-----------------------------------------

       $this->ipsclass->stronghold_set_cookie( $member['id'], $member['member_login_key'], 1 );

       //-----------------------------------------
       // Cookie me softly?
       //-----------------------------------------

       if ( $this->ipsclass->input['CookieDate'] )
       {
           $this->ipsclass->my_setcookie("member_id"   , $member['id']              , 1 );
           $this->ipsclass->my_setcookie("pass_hash"   , $member['member_login_key'], $_sticky, $_days );
       }

 

Так вот нижняя часть не отрабатывается, хотя должна. Закомментировал проверку на существование "$this->ipsclass->input['CookieDate']" и все, авторизация пошла.

 

Сейчас буду разбираться что это такое, может кто так сразу скажет почему во втором случае этот параметр теряется, и откуда он вообще берется?

Изменено пользователем fagediba
Ссылка на комментарий
Поделиться на других сайтах

из формы авторизации, галочка запомнить меня

такой галочки в капче нет, но если поднатужиться, то можно сделать

Ссылка на комментарий
Поделиться на других сайтах

Да, так и есть, пост дата теряется.

 

Значит исходный код верен, ничего там закомментировать не нужно, нужно внести изменение в шаблон. Админка - внешний вид - изменить хтмл шаблоны - skin_login (вход в форум) - loginCaptcha

 

Найти

<form action="{$this->ipsclass->base_url}act=Login&CODE=aftercaptcha" method="post" name="LOGIN" onsubmit="return ValidateForm()">
<input type="hidden" name="referer" value="{$this->ipsclass->input['referer']}" />
<input type="hidden" name="password" value="{$member['password']}" />
<input type="hidden" name="username" value="{$member['username']}" />

Добавить ниже

	<input type="hidden" name="CookieDate" value="{$this->ipsclass->input['CookieDate']}" />
<input type="hidden" name="Privacy" value="{$this->ipsclass->input['Privacy']}" />

 

Вроде пока прекрасно работает. Буду еще тестить, потом наверно всеже оформлю мод по нормальному.

Ссылка на комментарий
Поделиться на других сайтах

Вот держите мод

 

IPB AntiBruteForce v1.0

 

IPB antibruteforce v1.0.rar

 

Установка:

 

IPB 2.3.6 AntiBruteForce v1.0 by Babka http://fpteam-cheats.com

 

Made from mod loginCaptcha by Martin Aronsen

 

Mod installation

 

Upload folder "upload"

 

Log in to your Admin CP and go to the Components tab -> (FSY22) Universal Mod Installer -> Manage Mod Installations page. Look for the entry for this mod, click the grey Options button beside it, and click the Install link. The installer script will read the mod's XML file and determine the proper installation steps, then you can click the Proceed button to have it execute these actions.

 

 

 

 

File Edits

 

Просьба выложить txt файлом, форум съедает некоторые ньюансы

Изменено пользователем Arhar
Ссылка на комментарий
Поделиться на других сайтах

Присоединиться к обсуждению

Вы можете ответить сейчас, а зарегистрироваться позже. Если у вас уже есть аккаунт, войдите, чтобы ответить от своего имени.

Гость
Ответить в этой теме...

×   Вы вставили отформатированный текст.   Удалить форматирование

  Допустимо не более 75 смайлов.

×   Ваша ссылка была автоматически заменена на медиа-контент.   Отображать как ссылку

×   Ваши публикации восстановлены.   Очистить редактор

×   Вы не можете вставить изображения напрямую. Загрузите или вставьте изображения по ссылке.

Зарузка...
×
×
  • Создать...

Важная информация

Находясь на нашем сайте, вы соглашаетесь на использование файлов cookie, а также с нашим положением о конфиденциальности Политика конфиденциальности и пользовательским соглашением Условия использования.