Wiki source for BadBehavior


Show raw source

=====Bad Behavior=====

>>**See also**
~-[[ThirdPartyIntegration | Experimental 3rd party software integration in wikka]]
~-[[Docs:ThirdPartyInfo | 3rdparty software officially bundled with wikka]]
>>::c::

Bad Behavior is a set of PHP scripts which prevents spambots from accessing your site by analyzing their actual HTTP requests and comparing them to profiles from known spambots. It goes far beyond User-Agent and Referer, however. Bad Behavior is available for several PHP-based software packages, and also can be integrated in seconds into any PHP script. (quote from the [[http://www.bad-behavior.ioerror.us/ | homepage]]).

====Integration in wikka====

=== Bad-Behavior 1.2.x series ===
''these instructions are for version 1.2.1 but should work for the whole 1.2.x series''

~1. [[http://www.ioerror.us/software/bad-behavior/bad-behavior-download/ | download]] it
~2. unzip the file, go into the folder and make the following changes:
~3. add ##bad-behavior-wikkawiki.php## to the folder, with the following content:
%%(php;1)
<?php
/*
http://www.ioerror.us/software/bad-behavior/

Bad Behavior - detects and blocks unwanted Web accesses
Copyright (C) 2005 Michael Hampton

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/**
* Entry point for using bad behavior with wikkawiki.
*
* @author: {@link http://www.ioerror.us/software/bad-behavior/ Michael Hampton} (generic entry file)
* @author: {@link http://wikka.jsnx.com/NilsLindenberg Nils Lindenberg} (rewritten for wikka)
* @author: {Stefan Lindenberg} (simplification of the code)
*
* @version: 1.2
*/


//***Configuration***

// The database table name to use.
define('WP_BB_LOG', $wakka->config['table_prefix'].'bad_behavior_log');

define('WP_BB_CWD', dirname(__FILE__));

// Log failed requests to the database.
if ($wakka->config['bad-behavior-logging'] == 1) $wp_bb_logging = TRUE;
else $wp_bb_logging = TRUE;

// Log all requests to the database, not just failed requests.
if ($wakka->config['bad-behavior-logging'] == 2) $wp_bb_verbose_logging = TRUE;
else $wp_bb_verbose_logging = FALSE;

// How long to keep the logs around (in days).
$wp_bb_logging_duration = 7;

// Email address to contact you in case of problems
// This will be shown to users on the error page, which means it will
// be exposed to spammers! Bad Behavior will munge it automatically; you
// should NOT munge it here!
$wp_bb_email = $wakka->config['admin_email'];


//***Callbacks***

// return a UTC date in the format preferred by your database
function wp_bb_date() {
return gmdate('Y-m-d H:i:s');
}

// run a SQL query and return # of rows affected, or FALSE if query failed
function wp_bb_db_query($query) {
global $wakka;

$result = $wakka->Query($query);
if ($result === TRUE || $result === FALSE) $returnValue = $result;
else {
$data = mysql_fetch_row($result);
$query_parts = explode(" ",$query);
$mysql_statement = strtolower($query_parts[0]);
switch ($mysql_statement) {
case "insert":
case "delete":
case "update":
$returnValue = mysql_num_rows($result);
break;
case "select":
$returnValue = mysql_affected_rows();
break;
default:
if($data === FALSE) $returnValue = 0;
else $returnValue = 1;
}
mysql_free_result($result);
}
return $returnValue;
}

// Load core functions and do initial checks
require_once(WP_BB_CWD . "/bad-behavior-core.php");

?>
%%

~4. install the mysql-table (replace wikka_ in the first line with your table-prefix - must be the same as in the wikka.config!) :

%%
CREATE TABLE IF NOT EXISTS wikka_bad_behavior(
`id` int( 11 ) NOT NULL AUTO_INCREMENT ,
`ip` text NOT NULL ,
`date` datetime NOT NULL default '0000-00-00 00:00:00',
`request_method` text NOT NULL ,
`http_host` text,
`request_uri` text NOT NULL ,
`server_protocol` text NOT NULL ,
`http_referer` text,
`http_user_agent` text,
`http_headers` text NOT NULL ,
`request_entity` text NOT NULL ,
`denied_reason` text NOT NULL ,
`http_response` int( 3 ) NOT NULL ,
PRIMARY KEY ( `id` )
)
%%

~5. upload the whole folder to ##3rdparty/plugins/bad-behavior/##

~6. add the following line to ##wikka.php##
%%(php)
//load 'bad-behavior'
if ($wakka->config['bad-behavior'] == 1) require_once("3rdparty/plugins/bad-behavior/bad-behavior-wikkawiki.php");
%%

=> right before the %%(php;1171)// go !%%---

===Configuration===

add %%(php)
'bad-behavior' => '1',
'bad-behavior-logging' => '1',
%%

to your ##wikka.config.php##

**bad-behavior**:
- 0: don't run bad-behavior
- 1: run bad-behavior

**bad-behavior-logging**
- 0: don't log anything
- 1: log failed request
- 2: log all requests

=== Bad Behavior 2.0.x series ===
// note: this is a it's-working-for-me, i.e. an alpha version.//


~1. [[http://www.bad-behavior.ioerror.us/download/ | download it]]

~2. extract the zip-file and upload the content of the **subfolder** bad-behavior (i.e from admin.inc.php to whitelist.inc.php) to **3rdparty/plugins/bad-behavior**

~3. Add the following file as ##bad-behavior-wikkawiki.php## to the same folder:

%%(php;1)
<?php
/**
* Contains the functions and config entries needed by Bad Behavior 2.
*
* Only this file should be used as an entry point from within wikkawiki.
* It is based on the generic file of Bad Behavior 2.x and has been adjusted for the use with wikkawiki.
*
* @package 3rdparty
* @subpackage Bad Behavior
* @version $Id$
* @filesource
*
* @author {@link http://www.bad-behavior.ioerror.us/ Michael Hampton} (generic entry file)
* @author {@link http://www.wikkawiki.org/NilsLindenberg Nils Lindenberg} (adjusted for wikkawiki)
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*
*/

/*
Bad Behavior - detects and blocks unwanted Web accesses
Copyright (C) 2005-2006 Michael Hampton

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

As a special exemption, you may link this program with any of the
programs listed below, regardless of the license terms of those
programs, and distribute the resulting program, without including the
source code for such programs: ExpressionEngine

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Please report any problems to badbots AT ioerror DOT us
*/

/**
* Hold the directory of Bad Behavior 2 to protect it from being called directly.
*/
define('BB2_CWD', dirname(__FILE__).DIRECTORY_SEPARATOR);

/**
* Hold Bad Behavior Settings.
*/
$bb2_settings_defaults = array(
'log_table' => $wakka->GetConfigValue('table_prefix').'bad_behavior',
'display_stats' => true,
'strict' => false,
'verbose' => false
);

// Bad Behavior callback functions.

/**
* Return current time.
*
* @return string current time in MySQL format.
*/
function bb2_db_date() {
return gmdate('Y-m-d H:i:s');
}

/**
* Return affected rows from most recent query.
*
* not used.
*
* @return int number of affected rows from most recent query.
* @todo write function.
*/
function bb2_db_affected_rows() {
//return $this->getAffectedRows();
print "bb2_db_affected_rows";
}

/**
* Escape a string for database usage.
*
* @param string $string mandatory: string to be escaped.
* @return string MySQL escaped string.
*/
function bb2_db_escape($string) {
return mysql_real_escape_string($string);
}

/**
* Return the number of rows in a particular query.
*
* @return int number of row
*/
function bb2_db_num_rows($result) {
if ($result !== FALSE)
return count($result);
return 0;
}

/**
* Run a query and return the results, if any.
*
* Bad Behavior will use the return value here in other callbacks.
* Due to Wakka::Query() stopping in case of an error this will never return false.
*
* @uses Wakka::Query()
* @param string $query mandatory: MySQL-Query to be executed.
* @return mixed result of the query.
*/
function bb2_db_query($query) {
global $wakka;
return $wakka->Query($query);
}

/**
* Return all rows in a particular query.
*
* Should contain an array of all rows generated by calling mysql_fetch_assoc()
* or equivalent and appending the result of each call to an array.
*
* Not used.
*/
function bb2_db_rows($result) {
while ($row = mysql_fetch_assoc($result)) $return[] = $row;

mysql_free_result($result);
return $return;
}

/**
* Return emergency contact email address.
*
* @see wikka.config.php
* @uses Config::$admin_email
* @uses Wakka::GetConfigValue()
* @return string email adress of wikka admin
*/
function bb2_email() {
global $wakka;
return $wakka->GetConfigValue('admin_email');
}

/**
* Retrieve Bad Behavior 2 settings.
*
* Hardcoded in this file (see above)
* @return array settings for bb2
*/
function bb2_read_settings() {
global $bb2_settings_defaults;
return $bb2_settings_defaults;
}

/**
* Write settings to database.
*
* Not used.
* @return boolean FALSE
*/
function bb2_write_settings($settings) {
return false;
}

/**
* Install Bad Behavior 2.
*
* Not used, we'll use wikka-installer instead.
*
* @return boolean FALSE
*/
function bb2_install() {
return false;
}

/**
* Insert the javascript for the Screener into a html file.
*
* This is optional we'll fall back to cookies if you don't use it.
*/
function bb2_insert_head() {
global $bb2_javascript;
echo $bb2_javascript;
}

/**
* Display stats (enabled by default).
*
* Used by {{badbehavior}} action.
*/
function bb2_insert_stats($force = false) {
$settings = bb2_read_settings();

if ($force || $settings['display_stats']) {
$blocked = bb2_db_query("SELECT COUNT(*) FROM " . $settings['log_table'] . " WHERE `key` NOT LIKE '00000000'");
if ($blocked !== FALSE) {
return(sprintf('<p><a href="http://www.homelandstupidity.us/software/bad-behavior/">%1$s</a> %2$s <strong>%3$s</strong> %4$s</p>', __('Bad Behavior'), __('has blocked'), $blocked[0]["COUNT(*)"], __('access attempts in the last 7 days.')));
}
else return('Nobody blocked yet.');
}
else return('The display of Bad Behavior stats has been turned off.');
}

/**
* Return the top-level relative path of wherever we are (for cookies).
*/
function bb2_relative_path() {
global $wakka;
return $wakka->GetConfigValue("base_url");
}

// Calls inward to Bad Behavor itself.
require_once(BB2_CWD . "version.inc.php");
require_once(BB2_CWD . "core.inc.php");
//bb2_install();

bb2_start(bb2_read_settings());

?>
%%

~4. install the mysql-table (replace wikka_ in the first line with your table-prefix - must be the same as in the wikka.config!) :
%%
CREATE TABLE IF NOT EXISTS wikka_bad_behavior (
`id` INT(11) NOT NULL auto_increment,
`ip` TEXT NOT NULL,
`date` DATETIME NOT NULL default '0000-00-00 00:00:00',
`request_method` TEXT NOT NULL,
`request_uri` TEXT NOT NULL,
`server_protocol` TEXT NOT NULL,
`http_headers` TEXT NOT NULL,
`user_agent` TEXT NOT NULL,
`request_entity` TEXT NOT NULL,
`key` TEXT NOT NULL,
INDEX (`ip`(15)),
INDEX (`user_agent`(10)),
PRIMARY KEY (`id`) );
%%

~ 5. edit ##actions/header.php## and add the following line:
%%(php;29)
<?php bb2_insert_head(); #BB2 ?>
%%

behind

%%(php;28)
<base href="<?php echo $site_base ?>" />
%%

~ 6. edit ##wikka.php## and add the following line:

%%(php;221)
require_once('3rdparty/plugins/bad-behavior/bad-behavior-wikkawiki.php'); #BB2
%%

before the
%%(php;222)
/**
* Run the engine.
*/
%%

== Issues ==
- no config-options yet.
- it probably breaks with mode-rewrite=off
- not all of the functions are finished (they require some changes which would be better located in the core), but none of these is used (at least in 2.0.10)
- I should take a look at the version from Mike (see comments below)

----
CategoryDevelopment3rdParty CategoryDevelopmentAntiSpam
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki