Merhaba, Ziyaretçi. Lütfen giriş yapın veya üye olun.
Aktivasyon mailiniz gelmediyse buraya tıklayın.
09, 2008, 02:35:45 am
42744 Mesaj 8090 Konu Gönderen: 17931 Üye
Son üye: medist
Turk-Php.Com Forum  |  Yardım Forumları  |  PHP Yardım Forumu  |  PHP Class Deposu  |  Flood önlemek için class « önceki sonraki »
Sayfa: [1] Yazdır
Yazan Konu: Flood önlemek için class  (Okunma Sayısı 1816 defa)
phparmy
phparmy
PHP Stajyeri
**
Offline Offline

Mesaj Sayısı: 371


Elektronik imzam.


Üyelik Bilgileri
Flood önlemek için class
« : 09, 2006, 06:14:24 am »

class dosyası
Kod:
<?php

// ----------------------------------------------------------------------------
//
// class.floodblocker.php - FloodBlocker class, ver.0.01 (April 15, 2005)
//
// Description:
//   Class allowing to protect the scripts from flooding and to prevent
//   automatic download of the site from single IP.
//
// Author:
//   Vagharshak Tozalakyan <vagh@armdex.com>
//   This module was written by author on its leasure time.
//
// Warning:
//   This class is non commercial, non professional work. It should not have
//   unexpected results. However, if any damage is caused by this class the
//   author can not be responsible. The use of this class is at the risk of
//   the user.
//
// Requirements:
//   PHP >= 4.1.0
//
// ----------------------------------------------------------------------------


// Errors and warnings

define 'E_TMP_DIR',    'Incorrect temprorary directory specified.' );
define 'E_IP_ADDR',    'Incorrect IP address specified.' );
define 'E_LOG_FILE',   'Log file access error! Check permissions to write.' );
define 'E_CRON_FNAME''The name of cron file must begin with dot.' );
define 'E_CRON_FILE',  'Cron file access error! Check permissions to write.' );
define 'E_CRON_JOB',   'Unable to perform the cron job.' );


// Class definition

class FloodBlocker
{

  
// The directory where log files will be saved. Must have permissions to write.
  
var $logs_path;

  
// IP address of current connection. REMOTE_ADDR will be used by default.
  
var $ip_addr;

  
// An associative array of [$interval=>$limit] format, where $limit is the
  // number of possible requests during $interval seconds.
  
var $rules;

  
// The name of the cron file. Must begin with dot. Default filename is '.time'.
  
var $cron_file;

  
// Cron execution interval in seconds. 1800 secs (30 mins) by default.
  
var $cron_interval;

  
// After how many of seconds to consider a file as old? By default the files
  // will consider as old after 7200 secs (2 hours).
  
var $logs_timeout;


  
/*
    Description:
      Class constructor.
    Prototype:
      void FloodBlocker ( string logs_path, string ip = '' )
    Parameters:
      logs_path - the directory where log files will be saved
      ip - the ip address of the current connection,
           $_SERVER['REMOTE_ADDR'] will be used if ip=''
  */
  
function FloodBlocker $logs_path$ip '' )
  {

    if ( ! 
is_dir $logs_path ) )
      
trigger_error E_TMP_DIRE_USER_ERROR );

    
$logs_path str_replace '\\''/'$logs_path );
    if ( 
substr $logs_path, -) != '/' )
      
$logs_path .= '/';

    
$this->logs_path $logs_path;

    if ( empty ( 
$ip ) )
      
$ip $_SERVER['REMOTE_ADDR'];

    
$ip ip2long $ip );
    if ( 
$ip == -|| $ip === FALSE )
      
trigger_error E_IP_ADDRE_USER_ERROR );

    
$this->ip_addr $ip;

    
$this->rules = array ( );
    
$this->cron_file '.time';
    
$this->cron_interval 1800;  // 30 minutes
    
$this->logs_timeout 7200;  // 2 hours

  
}


  
/*
    Description:
      Used to check flooding. Generally this function acts as private method
      and will be called internally by public methods. However, it can be called
      directly when storing logs in db.
    Prototype:
      bool RawCheck ( array &info )
    Parameters:
      info - $interval=>$time, $interval=>$count array
    Return:
      FALSE if flood detected, otherwise - TRUE.
  */
  
function RawCheck ( &$info )
  {

    
$no_flood TRUE;

    foreach ( 
$this->rules as $interval=>$limit )
    {
      if ( ! isset ( 
$info[$interval] ) )
      {
        
$info[$interval]['time'] = time ( );
        
$info[$interval]['count'] = 0;
      }

      
$info[$interval]['count'] += 1;

      if ( 
time ( ) - $info[$interval]['time'] > $interval )
      {
        
$info[$interval]['count'] = 1;
        
$info[$interval]['time'] = time ( );
      }

      if ( 
$info[$interval]['count'] > $limit )
      {
        
$info[$interval]['time'] = time ( );
        
$no_flood FALSE;
      }

      
// The following two lines can be used for debugging
      // echo $info[$interval]['count'].'  ';
      // echo $info[$interval]['time'].'<br>';

    
}  // foreach

    
return $no_flood;

  }


  
/*
    Description:
      Checks flooding. Must be called after setting up all necessary properties.
    Prototype:
      bool CheckFlood ( )
    Return:
      FALSE if flood detected, otherwise - TRUE.
  */
  
function CheckFlood ( )
  {

    
$this->CheckCron ( );

    
$path $this->logs_path $this->ip_addr;

    if ( ! ( 
$f fopen $path'a+' ) ) )
      
trigger_error E_LOG_FILEE_USER_ERROR);

    
flock $fLOCK_EX );

    
$info fread $ffilesize $path ) + 10 );
    
$info unserialize$info );

    
$result $this->RawCheck $info );

    
ftruncate $f);
    
fwrite $fserialize$info ) );
    
fflush $f );

    
flock($fLOCK_UN);

    
fclose($f);

    return 
$result;

  }


  
/*
    Description:
      Checks the cron file and calls CronJob() to delete old entries from logs
      directory if the time-out is reached.
    Prototype:
      void CheckCron ( )
  */
  
function CheckCron ( )
  {

    if ( 
substr $this->cron_file0) != '.' )
    {
      
trigger_error E_CRON_FNAMEE_USER_WARNING );
      return;
    }

    
$path $this->logs_path $this->cron_file;

    if ( ! ( 
$f fopen $path'a+' ) ) )
    {
      
trigger_error E_CRON_FILEE_USER_WARNING );
      return;
    }

    
flock $fLOCK_EX );

    
$last_cron fread $ffilesize $path ) + 10 );
    
$last_cron abs intval $last_cron ) );

    if ( 
time ( ) - $last_cron $this->cron_interval )
    {
      
$this->CronJob ( );
      
$last_cron time ( );
    }

    
ftruncate $f);
    
fwrite $f$last_cron );
    
fflush $f );

    
flock $fLOCK_UN );

    
fclose $f );

  }


  
/*
    Description:
      Deletes all old files from logs directory, except the files starting
      with dot.
    Prototype:
      void CronJob ( )
  */
  
function CronJob ( )
  {

    
$path $this->logs_path;

    if ( ! ( 
$dir_hndl opendir $this->logs_path ) ) )
    {
      
trigger_error E_CRON_JOBE_USER_WARNING);
      return;
    }

    while ( 
$fname readdir $dir_hndl ) )
    {
      if ( 
substr$fname0) == '.' )
        continue;
      
clearstatcache ( );
      
$ftm filemtime $path $fname );
      if ( 
time ( ) - $ftm $this->logs_timeout )
        @
unlink $path $fname );
    }

    
closedir $dir_hndl );

  }

}  
// end of class definition



/*
  $flb = new FloodBlocker ( 'example/tmp-ips/' );
  $flb->rules = array ( 10=>5 );
  $res = $flb->CheckFlood ( );
  if ( $res )
    echo 'Succeed!';
  else
    die ( 'Too many requests! Please try later.' );
*/

?>


Kullanım Şekli
Kod:
<?php

  
// Place flood protection code at the top of the script you want to protect.
  // You can write protection code into separate file and include it in every
  // page of your site.

  // Sample protection code starts here...

  // Include the class definition module.

  
require_once ( '../class.floodblocker.php' );

  
// In the following line write the full path to temporary directory in which
  // you want to store flood counters. It is good idea to create such folder
  // somewhere outside your documents directory, to make it unaccessable from Web.
  // Don't forget that the directory must have permissions to write files in it.
  // IMPORTANT!
  // All files in this folder (except those that start with dot, e.g.'.htaccess')
  // will be deleted by FloodBlocker, so don't keep anything there.

  
$flb = new FloodBlocker 'tmp-ips/' );

  
// Create as many rules as you want...

  
$flb->rules = array (
    
10=>10,    // rule 1 - maximum 10 requests in 10 secs
    
60=>30,    // rule 2 - maximum 30 requests in 60 secs
    
300=>50,   // rule 3 - maximum 50 requests in 300 secs
    
3600=>200  // rule 4 - maximum 200 requests in 3600 secs
  
);

  
// At last call CheckFlood(), it will return FALSE if flood detected on any
  // of specified rules.

  
if ( ! $flb->CheckFlood ( ) )
    die ( 
'Too many requests! Please try later.' );

  
// ... that's all. Enjoy!

?>


<html>
<head>
<title>The title of my page...</title>
</head>
<body bgcolor="#cccccc">
<h1>Welcome to my page...</h1>
No flood was detected if you see the contents of this page...
</body>
</html>
Logged
Furstlip
PHP Stajyeri
**
Offline Offline

Mesaj Sayısı: 157


Üyelik Bilgileri WWW
Ynt: Flood önlemek için class
« Yanıtla #1 : 15, 2007, 12:09:24 pm »

Bu kod tam olarak ne işe yarıyor? Biraz açıklayabilirmisiniz?
Logged

bendeseni
Arya Emini
PHP Stajyeri
**
Offline Offline

Mesaj Sayısı: 218


Şebnem Ferah Fanatiği


Üyelik Bilgileri WWW
Ynt: Flood önlemek için class
« Yanıtla #2 : 14, 2007, 06:52:05 pm »

Derinlemesine inceleyemedim fakat dosya yazma fonksiyonlari gozume carpti. Muhtemelen bir takim kontroller var icinde. Onlari kontrol edip karar veren bir yapi olsa gerek. Paylasim icin tesekkurler. Inceledikten sonra guzel bir fikir verecegi kanaatindeyim.

Degisiklik: DDoS onleme yontemleri hakkinda da biseyler kasmak lazim aslinda.

Biri beni durdursun!
« Son Düzenleme: 14, 2007, 06:55:07 pm Gönderen: bendeseni » Logged

İLGİ olmadan BİLGİ olmaz...
www.sebnemferahfan.com
Furstlip
PHP Stajyeri
**
Offline Offline

Mesaj Sayısı: 157


Üyelik Bilgileri WWW
Ynt: Flood önlemek için class
« Yanıtla #3 : 15, 2007, 04:53:35 am »

Ddos konusundada flood konusundada önlem almak lazım. Her ikisininde nasıl yapıldıklarını detaylı olarak bilmesemde aşırı yoğunluk ile sistemi kasma amaçlı olduklarını biliyorum. Örnek verenlerin detaylı açıklama yapmaları verdikleri örneklerin kullanılmasını sağlayacaktır. Ne iş yaptığı, nasıl yaptığı ve nasıl kullanıldığına dair bilgi verilmeyen örnekler pek yararlı olmuyorlar... En azından ben nasıl çalıştığını bilmediğim kodları sayfalarıma eklemiyorum.
Logged

beyaz_ölüm
PHP Öğrencisi
*
Offline Offline

Mesaj Sayısı: 92


Üyelik Bilgileri
Ynt: Flood önlemek için class
« Yanıtla #4 : 27, 2007, 07:23:25 am »

DDOS'a önlemi nasıl alacaksın Smiley DOS desen hadi ama DDOS biraz zor be paşam!

Dos : Tek ip'den yapılan istek saldırısı , lamer programları buna örnek.

Ddos : bir çok kişi tarafından yapılan istek saldırısı , botnet buna örnek....
Logged
tespara
Yeni Kullanıcılar
*
Offline Offline

Mesaj Sayısı: 27


Üyelik Bilgileri WWW
Ynt: Flood önlemek için class
« Yanıtla #5 : 29, 2007, 05:55:31 pm »

bunu phpclass sitesinde n aldıysan bu kodlarda sorun var . ben bnu vbulletine uyguladım dosyaları sildi
Logged

Çok kaygı çekme, mukadder olan olur, takdir olunan rızkın da sana gelir.[Hz Muhammed (S.A.V)]
Elif Lam Mim. İnsanlar "inandık" deyip kurutlacaklarınımı sanırlar[Ankebut ,1]
phparmy
phparmy
PHP Stajyeri
**
Offline Offline

Mesaj Sayısı: 371


Elektronik imzam.


Üyelik Bilgileri
Ynt: Flood önlemek için class
« Yanıtla #6 : 30, 2007, 04:39:51 am »

Kod:
var $logs_path;
Bu özelliği yanlış ayarladığından olabilirmi.
Sadece tuttuğu logları siliyor diye biliyorum.
Ayrıca tutulan logların silinmemesini istiyorsan unlink fonksiyonunu koddan sil.

Logged
bendeseni
Arya Emini
PHP Stajyeri
**
Offline Offline

Mesaj Sayısı: 218


Şebnem Ferah Fanatiği


Üyelik Bilgileri WWW
Ynt: Flood önlemek için class
« Yanıtla #7 : 07, 2008, 09:41:17 am »

botnet hadisesinin ne olduğunu tesadüfen öğrenmiş bulundum. Düşmanı tanıma adına lamer sitelerine de takılmıyor değilim. Saldırıya uğrayan bir lamer sitesi bu terimi kullanmıştı küfürle karışık. Konu dağılmasın.

DoS ve DDoS gerçekten karmaşık. Birincisinde IP'yi kısıtlayarak aşama katedilebilir ama ikincisi gerçekten korkunç. Böyle bir isteğin sunucuya erişmeden İSS tarafından engellenmesi gerekli. Elimdeki tek bilgi bundan ibaret. Kafa muzurluğa çalışmadığı için de tecrübe etmeden bu durum nasıl aşılır bilemeyeceğim. Anca tecrübeyle kazanırım bunu ama böyle bir saldırının da tecrübesi, kazanmak isteyeceğim son tecrübe olur herhal. 7 - 8 yıldır geliştirdiğim sistemlerde bile ufak tefek boşluklar çıktığını gördükçe bu iş daha bi cesaret işi haline geliyor.

Flood koruması da sunucuya dosya yazdırmadan okumadan "değişken değişken" kullanmak fikrine merak sardım. Şu an deneme aşamasında olduğundan peşin konuşup yamulmak istemiyorum ama işe yarayacak gibi görünüyor. Çalışma sistemi, sayfadaki form bilgilerini taşıyan değişkenlerin değişken olması yapısı üzerine kurulu. Böylece herhangi bir dosyaya yazıp okumakla vakit kaybedilmeyecek falan fişmekan. Küçük çaplı bir örnek üzerinde çalışıyorum. Aslında hazır fakat hala geliştirme aşamasında olduğu için şimdilik yayınlamayı düşünmüyorum. Bilgi paylaşmak istememek olarak algılanmasın lütfen. Arama motorlarında henüz görünmesini istemediğim bazı çalışmalar bu sayfadan referans alarak motorlarda yerini almışlar, ondan dolayı. Sistemi asıl çalışmadan izole edip yeniden döneceğim.

Pişkin pişkin sırıtmayın, deli değilim. Sadece az buçuk bilgimi konuşturarak biri beni tutsun demiştim Wink

Saygılar efem..
Logged

İLGİ olmadan BİLGİ olmaz...
www.sebnemferahfan.com
turker
türker
PHP Öğrencisi
*
Offline Offline

Mesaj Sayısı: 115


aggressiveness


Üyelik Bilgileri WWW
Ynt: Flood önlemek için class
« Yanıtla #8 : 07, 2008, 10:57:41 am »

DDOSu düşünmesi gerekenler uyguluma geliştirenler değil, zira öyle veya böyle apache, myql ve php isteklere cevap verdiği sürece saldırgan amacına ulaşıyor demektir. O yüzden sunucuyu yöneten kişi bu saldırganı bu servislere ulaşamadan olabildiğince engellemesi lazım.
Logged

Sayfa: [1] Yazdır 
« önceki sonraki »
Gitmek istediğiniz yer:  


Turk-Php.Com Forum | SMF Forum Software © 2005, Simple Machines LLC. All Rights Reserved.