From cb1221013251b4e9cba8e129edc6b8dbd8fd5145 Mon Sep 17 00:00:00 2001
From: Till Brehm <tbrehm@ispconfig.org>
Date: Mon, 25 Aug 2014 09:33:09 -0400
Subject: [PATCH] FS#3640 - Add Intrusion Detection System

---
 interface/lib/classes/db_mysql.inc.php |   47 +++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 47 insertions(+), 0 deletions(-)

diff --git a/interface/lib/classes/db_mysql.inc.php b/interface/lib/classes/db_mysql.inc.php
index 56d43f8..b96b8d0 100644
--- a/interface/lib/classes/db_mysql.inc.php
+++ b/interface/lib/classes/db_mysql.inc.php
@@ -121,6 +121,52 @@
 		parent::query( 'SET NAMES '.$this->dbCharset);
 		parent::query( "SET character_set_results = '".$this->dbCharset."', character_set_client = '".$this->dbCharset."', character_set_connection = '".$this->dbCharset."', character_set_database = '".$this->dbCharset."', character_set_server = '".$this->dbCharset."'");
 	}
+	
+	private function securityScan($string) {
+		global $app, $conf;
+		
+		// get security config
+		if(isset($app)) {
+			$app->uses('getconf');
+			$ids_config = $app->getconf->get_security_config('ids');
+			
+			if($ids_config['sql_scan_enabled'] == 'yes') {
+				
+				$string_orig = $string;
+				
+				//echo $string;
+				$chars = array(';', '#', '/*', '*/', '--', ' UNION ', '\\\'', '\\"');
+		
+				$string = str_replace('\\\\', '', $string);
+				$string = preg_replace('/(^|[^\\\])([\'"])(.*?[^\\\])\\2/is', '$1', $string);
+				$ok = true;
+
+				if(substr_count($string, "`") % 2 != 0 || substr_count($string, "'") % 2 != 0 || substr_count($string, '"') % 2 != 0) {
+					$app->log("SQL injection warning (" . $string_orig . ")",2);
+					$ok = false;
+				} else {
+					foreach($chars as $char) {
+						if(strpos($string, $char) !== false) {
+							$ok = false;
+							$app->log("SQL injection warning (" . $string_orig . ")",2);
+							break;
+						}
+					}
+				}
+				if($ok == true) {
+					return true;
+				} else {
+					if($ids_config['sql_scan_action'] == 'warn') {
+						// we return false in warning level.
+						return false;
+					} else {
+						// if sql action = 'block' or anything else then stop here.
+						$app->error('Possible SQL injection. All actions have been logged.');
+					}
+				}
+			}
+		}
+	}
 
 	public function query($queryString) {
 		global $conf;
@@ -143,6 +189,7 @@
 				}
 			}
 		} while($ok == false);
+		$this->securityScan($queryString);
 		$this->queryId = parent::query($queryString);
 		$this->updateError('DB::query('.$queryString.') -> mysqli_query');
 		if($this->errorNumber && $conf['demo_mode'] === false) debug_print_backtrace();

--
Gitblit v1.9.1