Content API for Shopping not working in OpenCart - opencart2.x

I am trying to integrate the Content API for Shopping in OpenCart into my PHP app and getting this error:
Fatal error: Uncaught exception 'GSC_ParseError' with message 'Not
Found' in
/home/public_html/admin/controller/module/GShoppingContent.php:2805
Stack trace: #0
/home/public_html/admin/controller/module/GShoppingContent.php(980):
_GSC_AtomParser::parse('Not Found') #1 /home/public_html/admin/controller/module/contentapi.php(76):
GSC_Client->insertProduct(Object(GSC_Product)) #2 [internal function]:
ControllerModuleContentApi->index(Array) #3
/home//public_html/vqmod/vqcache/vq2-system_modification_system_engine_action.php(71):
call_user_func(Array, Array) #4
/home//public_html/vqmod/vqcache/vq2-system_engine_front.php(89):
Action->execute(Object(Registry)) #5
/home//public_html/vqmod/vqcache/vq2-system_engine_front.php(63):
Front->execute(Object(Action)) #6
/home//public_html/admin/index.php(175):
Front->dispatch(Object(Action), Object(Action)) #7 {main} thrown in
/home//public_html/admin/controller/module/GShoppingContent.php on
line 2805
Here's my code:
require_once('GShoppingContent.php');
class ControllerModuleContentApi extends Controller {
private $error = array();
public function index() {
$this->load->language('module/contentapi');
$this->db->query("
CREATE TABLE IF NOT EXISTS `contentapi` (
`contentapiid` int(11) NOT NULL AUTO_INCREMENT,
`contentapimerchantid` varchar(256) NOT NULL,
`contentapiemail` varchar(256) NOT NULL,
`contentapipassword` varchar(256) NOT NULL,
PRIMARY KEY (`contentapiid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
");
$contentAPI11=$this->db->query("select * from contentapi");
$data['contentapidata'] = $contentAPI11->rows;
if (isset($this->request->post['merchantid']) && isset($this->request->post['GoogleMerchantEmail']) && isset($this->request->post['GoogleMerchantPassword'] )) {
$merchantid=$this->request->post['merchantid'];
$GoogleMerchantEmail=$this->request->post['GoogleMerchantEmail'];
$GoogleMerchantPassword=$this->request->post['GoogleMerchantPassword'];
$primaryid=$this->request->post['primaryid'];
$this->db->query("UPDATE contentapi SET contentapimerchantid='$merchantid',contentapiemail='$GoogleMerchantEmail',contentapipassword='$GoogleMerchantPassword' where contentapiid='$primaryid'");
}
$retrieveapidetails=$this->db->query("select * from contentapi");
if($retrieveapidetails->num_rows>0)
{
$retrieveapidetails1=$retrieveapidetails->rows;
foreach($retrieveapidetails1 as $retrieveapidetails2)
{
$contentapimerchantid=$retrieveapidetails2["contentapimerchantid"];
$contentapiemail=$retrieveapidetails2["contentapiemail"];
$contentapipassword=$retrieveapidetails2["contentapipassword"];
}
$retrieveproducts=$this->db->query("select oc_product.model,oc_product.sku,oc_product.price,oc_product.image,oc_product_description.name,oc_product_description.description from oc_product,oc_product_description where oc_product.product_id=oc_product_description.product_id");
$retrieveproducts1=$retrieveproducts->rows;
$client = new GSC_Client($contentapimerchantid);
$client->login($contentapiemail, $contentapipassword);
foreach($retrieveproducts1 as $retrieveproducts2)
{
$productid=$retrieveproducts2["product_id"];
$productname=$retrieveproducts2["name"];
$productmodel=$retrieveproducts2["model"];
$productprice=$retrieveproducts2["price"];
$productimage=$retrieveproducts2["image"];
$productsku=$retrieveproducts2["sku"];
$productdescription=$retrieveproducts2["description"];
$product = new GSC_Product();
$product->setTitle($productname);
$product->setDescription($productdescription);
$link = 'https://testingsite.com/index.php?route=product/product&product_id=' . $productid;
$product->setProductLink($link);
$product->setSKU($productsku);
$product->setImageLink('https://testingsite.com/'.$productimage);
$product->setBrand($productimage);
$product->setPrice($productprice, 'usd');
$entry = $client->insertProduct($product);
}
}

Related

Receiving error within Smartthings Device Handler

I am receiving the below error when trying to compile the device_handler code for the Sylvania Smart+ Plug. The code comes from https://images-na.ssl-images-amazon.com/images/I/71PrgM-PamL.pdf
The error:
Org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: script_dth_metadata_0631e407_ffd8_4ceb_b49a_877fd47635df: 94: expecting ''', found '\r' # line 94, column 55. nalResult.value == "on" ? '{{ ^ 1 error
Line 94:
def descriptionText = finalResult.value == "on" ? '{{
metadata {
definition (name: "SYLVANIA Smart Plug", namespace: "ledvanceDH", author:
"Ledvance") {
capability "Actuator"
capability "Switch"
capability "Power Meter"
capability "Configuration"
capability "Refresh"
capability "Sensor"
capability "Health Check"
fingerprint profileId: "C05E", inClusters:
"1000,0000,0003,0004,0005,0006,0B04,FC0F", outClusters: "0019", manufacturer: "OSRAM",
model: "Plug 01", deviceJoinName: "SYLVANIA Smart Plug"
fingerprint profileId: "0104", inClusters:
"0000,0003,0004,0005,0006,0B05,FC01,FC08", outClusters: "0003,0019", manufacturer:
"LEDVACE", model: "PLUG", deviceJoinName: "SYLVANIA Smart Plug"
}
// simulator metadata
simulator {
// status messages
status "on": "on/off: 1"
status "off": "on/off: 0"
// reply messages
reply "zcl on-off on": "on/off: 1"
reply "zcl on-off off": "on/off: 0"
}
preferences {
section {
image(name: 'educationalcontent', multiple: true, images: [
"http://cdn.devicegse.smartthings.com/Outlet/US/OutletUS1.jpg",
"http://cdn.devicegse.smartthings.com/Outlet/US/OutletUS2.jpg"
])
}
}
// UI tile definitions
tiles(scale: 2) {
multiAttributeTile(name:"switch", type: "lighting", width: 6, height: 4,
canChangeIcon: true){
tileAttribute ("device.switch", key: "PRIMARY_CONTROL") {
attributeState "on", label: 'On', action: "switch.off",
icon: "st.Appliances.appliances17", backgroundColor: "#79b821", nextState: "turningOff"
attributeState "off", label: 'Off', action: "switch.on",
icon: "st.Appliances.appliances17", backgroundColor: "#565C51", nextState: "turningOn"
attributeState "turningOn", label: 'Turning On', action:
"switch.off", icon: "st.Appliances.appliances17", backgroundColor: "#60903A", nextState:
"turningOff"
attributeState "turningOff", label: 'Turning Off', action:
"switch.on", icon: "st.Appliances.appliances17", backgroundColor: "#CACACA", nextState:
"turningOn"
}
tileAttribute ("power", key: "SECONDARY_CONTROL") {
attributeState "power", label:'${currentValue} W'
}
}
standardTile("refresh", "device.power", inactiveLabel: false, decoration:
"flat", width: 2, height: 2) {
state "default", label:'', action:"refresh.refresh",
icon:"st.secondary.refresh"
}
main "switch"
details(["switch","refresh"])
}
}
// Parse incoming device messages to generate events
def parse(String description) {
log.debug "description is $description"
def finalResult = zigbee.getKnownDescription(description)
def event = [:]
//TODO: Remove this after getKnownDescription can parse it automatically
if (!finalResult && description!="updated")
finalResult =
getPowerDescription(zigbee.parseDescriptionAsMap(description))
if (finalResult) {
log.info "final result = $finalResult"
if (finalResult.type == "update") {
log.info "$device updates: ${finalResult.value}"
event = null
}
else if (finalResult.type == "power") {
def powerValue = (finalResult.value as Integer)/10
event = createEvent(name: "power", value: powerValue,
descriptionText: '{{ device.displayName }} power is {{ value }} Watts', translatable:
true)
/*
Dividing by 10 as the Divisor is 10000 and unit is kW for
the device. AttrId: 0302 and 0300. Simplifying to 10
power level is an integer. The exact power level with
correct units needs to be handled in the device type
to account for the different Divisor value (AttrId: 0302)
and POWER Unit (AttrId: 0300). CLUSTER for simple metering is 0702
*/
}
else {
def descriptionText = finalResult.value == "on" ? '{{
device.displayName }} is On' : '{{ device.displayName }} is Off'
event = createEvent(name: finalResult.type, value:
finalResult.value, descriptionText: descriptionText, translatable: true)
}
}
else {
def cluster = zigbee.parse(description)
if (cluster && cluster.clusterId == 0x0006 && cluster.command == 0x07){
if (cluster.data[0] == 0x00) {
log.debug "ON/OFF REPORTING CONFIG RESPONSE: " + cluster
event = createEvent(name: "checkInterval", value: 60 * 12,
displayed: false, data: [protocol: "zigbee", hubHardwareId: device.hub.hardwareID])
}
else {
log.warn "ON/OFF REPORTING CONFIG FAILED- error
code:${cluster.data[0]}"
event = null
}
}
else {
log.warn "DID NOT PARSE MESSAGE for description : $description"
log.debug "${cluster}"
}
}
return event
}
def off() {
zigbee.off()
}
def on() {
zigbee.on()
}
/**
* PING is used by Device-Watch in attempt to reach the Device
* */
def ping() {
return zigbee.onOffRefresh()
}
def refresh() {
zigbee.onOffRefresh() + zigbee.electricMeasurementPowerRefresh()
}
def configure() {
// Device-Watch allows 2 check-in misses from device + ping (plus 1 min lag time)
// enrolls with default periodic reporting until newer 5 min interval is confirmed
sendEvent(name: "checkInterval", value: 2 * 10 * 60 + 1 * 60, displayed: false,
data: [protocol: "zigbee", hubHardwareId: device.hub.hardwareID])
// OnOff minReportTime 0 seconds, maxReportTime 5 min. Reporting interval if no
activity
refresh() + zigbee.onOffConfig(0, 300) + powerConfig()
}
//power config for devices with min reporting interval as 1 seconds and reporting
interval if no activity as 10min (600s)
//min change in value is 01
def powerConfig() {
[
"zdo bind 0x${device.deviceNetworkId} 1 ${endpointId} 0x0B04
{${device.zigbeeId}} {}", "delay 2000",
"zcl global send-me-a-report 0x0B04 0x050B 0x29 1 600 {05 00}",
//The send-me-a-report is custom to the attribute type for CentraLite
"delay 200",
"send 0x${device.deviceNetworkId} 1 ${endpointId}", "delay 2000"
]
}
private getEndpointId() {
new BigInteger(device.endpointId, 16).toString()
}
//TODO: Remove this after getKnownDescription can parse it automatically
def getPowerDescription(descMap) {
def powerValue = "undefined"
if (descMap.cluster == "0B04") {
if (descMap.attrId == "050b") {
if(descMap.value!="ffff")
powerValue = zigbee.convertHexToInt(descMap.value)
}
}
else if (descMap.clusterId == "0B04") {
if(descMap.command=="07"){
return [type: "update", value : "power (0B04) capability configured
successfully"]
}
}
if (powerValue != "undefined"){
return [type: "power", value : powerValue]
}
else {
return [:]
}
}
I should have thought of it sooner... The problem is with the copy/paste. The long lines were broken by a "return". I removed the returns and the script compiled.

Convert HQL to SparkSQL

I'm trying to convert HQL to Spark.
I have the following query (Works in Hue with Hive editor):
select reflect('java.util.UUID', 'randomUUID') as id,
tt.employee,
cast( from_unixtime(unix_timestamp (date_format(current_date(),'dd/MM/yyyy HH:mm:ss'), 'dd/MM/yyyy HH:mm:ss')) as timestamp) as insert_date,
collect_set(tt.employee_detail) as employee_details,
collect_set( tt.emp_indication ) as employees_indications,
named_struct ('employee_info', collect_set(tt.emp_info),
'employee_mod_info', collect_set(tt.emp_mod_info),
'employee_comments', collect_set(tt.emp_comment) )
as emp_mod_details,
from (
select views_ctr.employee,
if ( views_ctr.employee_details.so is not null, views_ctr.employee_details, null ) employee_detail,
if ( views_ctr.employee_info.so is not null, views_ctr.employee_info, null ) emp_info,
if ( views_ctr.employee_comments.so is not null, views_ctr.employee_comments, null ) emp_comment,
if ( views_ctr.employee_mod_info.so is not null, views_ctr.employee_mod_info, null ) emp_mod_info,
if ( views_ctr.emp_indications.so is not null, views_ctr.emp_indications, null ) employees_indication,
from
( select * from views_sta where emp_partition=0 and employee is not null ) views_ctr
) tt
group by employee
distribute by employee
First, What I'm trying is to write it in spark.sql as follow:
sparkSession.sql("select reflect('java.util.UUID', 'randomUUID') as id, tt.employee, cast( from_unixtime(unix_timestamp (date_format(current_date(),'dd/MM/yyyy HH:mm:ss'), 'dd/MM/yyyy HH:mm:ss')) as timestamp) as insert_date, collect_set(tt.employee_detail) as employee_details, collect_set( tt.emp_indication ) as employees_indications, named_struct ('employee_info', collect_set(tt.emp_info), 'employee_mod_info', collect_set(tt.emp_mod_info), 'employee_comments', collect_set(tt.emp_comment) ) as emp_mod_details, from ( select views_ctr.employee, if ( views_ctr.employee_details.so is not null, views_ctr.employee_details, null ) employee_detail, if ( views_ctr.employee_info.so is not null, views_ctr.employee_info, null ) emp_info, if ( views_ctr.employee_comments.so is not null, views_ctr.employee_comments, null ) emp_comment, if ( views_ctr.employee_mod_info.so is not null, views_ctr.employee_mod_info, null ) emp_mod_info, if ( views_ctr.emp_indications.so is not null, views_ctr.emp_indications, null ) employees_indication, from ( select * from views_sta where emp_partition=0 and employee is not null ) views_ctr ) tt group by employee distribute by employee")
But I got the following exception:
Exception in thread "main" org.apache.spark.SparkException: Job
aborted due to stage failute: Task not serializable:
java.io.NotSerializableException:
org.apache.spark.unsafe.types.UTF8String$IntWrapper
-object not serializable (class : org.apache.spark.unsafe.types.UTF8String$IntWrapper, value:
org.apache.spark.unsafe.types.UTF8String$IntWrapper#30cfd641)
If I'm trying to run my query without collect_set function its work, It's can fail because struct column types in my table?
How can I write my HQL query in Spark / fix my exception?

Not able to parse JsonPath in restassured

Using Restassured 3.0.1
I have a Json ::
json = {
"prices": {
"Test": {
"PriceMap": {
"30": "295"
}
}
}
}
JsonPath jsonPath = new JsonPath(json);
jsonPath.get("prices.Test.PriceMap.*")
getting error :
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected token: * # line 1, column 48.
otObject.prices.Test.PriceMap.*
You can use the getMap call to get the object as a map -- jsonPath.getMap("prices.Test.PriceMap")
System.out.println(jsonPath.getMap("prices.Test.PriceMap").keySet());
//Output : [30]
System.out.println(jsonPath.getMap("prices.Test.PriceMap").values());
//[295]
System.out.println(jsonPath.getMap("prices.Test.PriceMap").get("30"));
//295

Problems with access database in linux

We have a strange project that MUST interact with an MSAccess Database over a linux machine.
After reading different blogs, we have been able to make some readings over existing tables, but, if we try to make an insert or some special queries it fails with a connection has been restarted message.
I'll try to explain all what we have tried.
First of all, we have upgraded our system to the latest version of LAMP because it seems that there were some problems with odbc libraries.
After that, we added the PDO connection as described here.
https: //gist.github.com/amirkdv/9672857
sudo nano /etc/odbcinst.ini
[MDBTools]
Description = MDBTools Driver
Driver = /usr/lib/x86_64-linux-gnu/odbc/libmdbodbc.so.1
Setup = /usr/lib/x86_64-linux-gnu/odbc/libmdbodbc.so.1
FileUsage = 1
UsageCount = 2
After that, we have restarted apache, and it seems that select queries work correctly.
We have use the following examples with some small modifications.
http://coursesweb.net/php-mysql/pdo-select-query-fetch
Our database have a table call test with the following information:
CREATE TABLE `test` (
`Id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50),
`surname` VARCHAR(50),
`count` INTEGER
) ENGINE=myisam DEFAULT CHARSET=utf8;
SET autocommit=1;
INSERT INTO `test` () VALUES (1, 'john', 'smith', 100);
INSERT INTO `test` () VALUES (2, 'Mary', 'simmons', 200);
INSERT INTO `test` () VALUES (3, 'Jane', 'Black', 300);
If I launch the following php file
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Ejemplo de ODBC</title>
<body>
<?php
$mdb_file="/var/www/Temp/Example.mdb";
$uname = explode(" ",php_uname());
$os = $uname[0];
switch ($os){
case 'Windows':
$driver = '{Microsoft Access Driver (*.mdb)}';
break;
case 'Linux':
$driver = 'MDBTools';
break;
default:
exit("Don't know about this OS");
}
try{
$connect_string = "Driver={$driver};DBQ={$mdb_file};";
$dataSourceName = "odbc:" . $connect_string;
$connection = new PDO($dataSourceName);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'SELECT id, name, surname FROM test';
$result = $connection->query($query);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
// Parse the result set
foreach($result as $row) {
print_r ("<br>");
print_r ($row);
}
}
$connection = null;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
die();
} catch (Exception $e) {
echo "Exception: <br>".$e->getMessage();
die();
}
?>
</body>
</html>
As a result we get the following rows:
Array ( [id] => 1 [0] => 1 [count] => 100 [1] => 100 [name] => john [2] => john [surname] => smith [3] => smith )
Array ( [id] => 2 [0] => 2 [count] => 200 [1] => 200 [name] => Mary [2] => Mary [surname] => simmons [3] => simmons )
Array ( [id] => 3 [0] => 3 [count] => 300 [1] => 300 [name] => Jane [2] => Jane [surname] => Black [3] => Black )
So selects seems to work.
Now if I try an easy insert
$query = 'insert into test (id, count) values (4,400)';
$result = $connection->query($query);
I receive a message of reset connection:
La conexión al servidor fue reiniciada mientras la página se cargaba.
El sitio podría estar no disponible temporalmente o demasiado ocupado. Vuelva a intentarlo en unos momentos.
Si no puede cargar ninguna página, compruebe la conexión de red de su equipo.
Si su equipo o red están protegidos por un cortafuegos o proxy, asegúrese de que Firefox tiene permiso para acceder a la web.
So I have added debug over php
http: //jrs-s.net/2012/05/24/enabling-core-dumps-on-apache2-2-on-debian/
sudo apt-get install apache2-dbg libapr1-dbg libaprutil1-dbg
sudo nano /etc/apache2/apache2.conf
CoreDumpDirectory /tmp/apache2-dumps
mkdir /tmp/apache2-dumps ;
chmod 777 /tmp/apache2-dumps
sudo /etc/init.d/apache2 restart
And after launching my php file I see that on the dump folder I have a new core file.
So I exec sudo gdb apache2 /tmp/apache2-dumps/core
and when I get the (gdb) prompt I exec "bt" command getting the following info:
#0 0x00007ff38c49c3b1 in vfprintf () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00007ff38c55a344 in __vsprintf_chk () from /lib/x86_64-linux-gnu/libc.so.6
#2 0x00007ff37cbf538f in mdb_sql_error () from /usr/lib/x86_64-linux-gnu/libmdbsql.so.2
#3 0x00007ff37cbf6cbb in ?? () from /usr/lib/x86_64-linux-gnu/libmdbsql.so.2
#4 0x00007ff37cbf6691 in mdb_sql_run_query () from /usr/lib/x86_64-linux-gnu/libmdbsql.so.2
#5 0x00007ff37d012640 in ?? () from /usr/lib/x86_64-linux-gnu/odbc/libmdbodbc.so.1
#6 0x00007ff37c4e3c4a in ?? () from /usr/lib/x86_64-linux-gnu/libodbccr.so.1
#7 0x00007ff37ecc3d70 in SQLExecute () from /usr/lib/x86_64-linux-gnu/libodbc.so.1
#8 0x00007ff37e69923c in odbc_stmt_execute (stmt=0x7ff38d203338) at /build/buildd/php5-5.5.12+dfsg/ext/pdo_odbc/odbc_stmt.c:173
#9 0x00007ff3861ff59c in zim_PDO_query (ht=1, return_value=0x7ff38d203280, return_value_ptr=0x0, this_ptr=0x7ff38d202dd0, return_value_used=1) at /build/buildd/php5-5.5.12+dfsg/ext/pdo/pdo_dbh.c:1134
#10 0x00007ff389201819 in dtrace_execute_internal (execute_data_ptr=<optimized out>, fci=<optimized out>, return_value_used=<optimized out>) at /build/buildd/php5-5.5.12+dfsg/Zend/zend_dtrace.c:97
#11 0x00007ff3892bc15e in zend_do_fcall_common_helper_SPEC (execute_data=0x7ff38d1cf0c0) at /build/buildd/php5-5.5.12+dfsg/Zend/zend_vm_execute.h:552
#12 0x00007ff3892809c8 in execute_ex (execute_data=0x7ff38d1cf0c0) at /build/buildd/php5-5.5.12+dfsg/Zend/zend_vm_execute.h:363
#13 0x00007ff389201706 in dtrace_execute_ex (execute_data=0x7ff38d1cf0c0) at /build/buildd/php5-5.5.12+dfsg/Zend/zend_dtrace.c:73
#14 0x00007ff389213243 in zend_execute_scripts (type=8, retval=0x0, file_count=3) at /build/buildd/php5-5.5.12+dfsg/Zend/zend.c:1316
#15 0x00007ff3891b0f1c in php_execute_script (primary_file=0x7fff3030a700) at /build/buildd/php5-5.5.12+dfsg/main/main.c:2506
#16 0x00007ff3892bf6dd in php_handler (r=0x7ff38d15d0a0) at /build/buildd/php5-5.5.12+dfsg/sapi/apache2handler/sapi_apache2.c:667
#17 0x00007ff38d341008 in ap_run_handler (r=0x7ff38d15d0a0) at config.c:170
#18 0x00007ff38d3415fe in ap_invoke_handler (r=0x7ff38d15d0a0) at config.c:439
#19 0x00007ff38d357e3a in ap_process_async_request (r=0x7ff38d15d0a0) at http_request.c:317
#20 0x00007ff38d357f9f in ap_process_request (r=0x7ff38d15d0a0) at http_request.c:363
#21 0x00007ff38d3544a5 in ap_process_http_sync_connection (c=0x7ff38d165290) at http_core.c:190
#22 ap_process_http_connection (c=0x7ff38d165290) at http_core.c:231
#23 0x00007ff38d34ac48 in ap_run_process_connection (c=0x7ff38d165290) at connection.c:41
#24 0x00007ff389b8a633 in child_main (child_num_arg=<optimized out>) at prefork.c:704
#25 0x00007ff389b8a88c in make_child (s=0x7ff38d2adde0, slot=9) at prefork.c:800
#26 0x00007ff389b8b867 in perform_idle_server_maintenance (p=<optimized out>) at prefork.c:902
#27 prefork_run (_pconf=<optimized out>, plog=<optimized out>, s=<optimized out>) at prefork.c:1090
#28 0x00007ff38d325ed6 in ap_run_mpm (pconf=0x7ff38d2db028, plog=0x7ff38d2a9028, s=0x7ff38d2adde0) at mpm_common.c:98
#29 0x00007ff38d31f448 in main (argc=3, argv=0x7fff3030ae18) at main.c:777
But I don't know how to continue.
Could you help me?
David, hi
It's been a while since I did Access DB import into mysql and unfortunately I do not have access to that system anymore. But as far as I remember most of our strange problems where solved by switching the language settings form utf-8 to iso-8859-1 in the server configuration.
Maybe this is a point into the right direction?

The sure way to protect against XSS?

I've looked through the questions and I haven't seen anyone ask this yet.
What is the for sure method to remove any sort of XSS attempts in some user submitted content? I know that < and > should be converted to < and > respectively but I've heard mention that encoding differences can get around this too.
Supposing a whitelist, what are all the steps to completely clean some user submitted content to ensure that no XSS vulnerabilities exist?
There is no absolute security concering XSS since people find new attack vectors every day. Sometimes XSS is even a browser bug you cant do anything about (excep some workarounds).
To get the idea of the complexity look at this (incomplete) xss attack cheat sheet.
http://ha.ckers.org/xss.html
Guess you should make yourself a XSS expert or hire one to reach your goal.
You can start by inspecting the attack vectors from the given link above, try to understand why it can work and make sure you prevent it.
Another great way of preventing XSS is to make sure you accept only stuff you expect instead of blocking stuff you know is bad. (i.e. whitelisting instead of blacklisting)
http://htmlpurifier.org/ - HTMLPurifier could be of help
ps: don't create your own code, there is no way you can cover all the issues. rely on the continually developed libraries such as HTMLPurifier.
Old Question, but XSS isn't old, its still up to date....
So, i would recommend you to have a look for the OWASP XSS Prevention Cheat Sheet and for a good overview the OWASP XSS overview
And if you need a really good way for escaping, have a look for the ESAPI Encoder API
Some of the holes I've seen fixed in different frameworks have been so unreal I don't get how they were found out. If you want to be 100% sure don't let users post content.
Proving a negative is a difficult proposition - as googletorp points out, the only 100% solution is to not have the problem in the first place.
Functionally, the xss attack cheat sheet at ha.ckers.org is a good place to start, as is a whitelisting approach - rather than disallowing things known to be bad, only allow things known to be good.
PHP-Firewall
against XSS etc
http://www.php-firewall.info/
http://code.google.com/p/php-firewall/
<?php
/************************************************************************/
/* PHP Firewall: Universal Firewall for WebSite */
/* ============================================ */
/* Write by Cyril Levert */
/* Copyright (c) 2009-2010 */
/* http://www.php-firewall.info */
/* dev#php-maximus.org */
/* Others projects: */
/* CMS PHP Maximus ( with mysql database ) www.php-maximus.org */
/* Blog PHP Minimus ( with mysqli database ) www.php-minimus.org */
/* Mini CMS PHP Nanomus ( without database ) www.php-nanomus.org */
/* Stop Spam Referer ( without database ) www.stop-spam-referer.info */
/* Twitter clone ( PHP Kweeker CMS ) www.twitter.php-minimus.org */
/* PHP Firewall ( without database ) www.php-firewall.info */
/* Personnal blog www.cyril-levert.info */
/* Release version 1.0.3 */
/* Release date : 12-04-2010 */
/* */
/* This program is free software. */
/************************************************************************/
/** IP Protected */
$IP_ALLOW = array();
/** configuration define */
define('PHP_FIREWALL_LANGUAGE', 'english' );
define('PHP_FIREWALL_ADMIN_MAIL', '' );
define('PHP_FIREWALL_PUSH_MAIL', false );
define('PHP_FIREWALL_LOG_FILE', 'logs' );
define('PHP_FIREWALL_PROTECTION_UNSET_GLOBALS', true );
define('PHP_FIREWALL_PROTECTION_RANGE_IP_DENY', true );
define('PHP_FIREWALL_PROTECTION_RANGE_IP_SPAM', false );
define('PHP_FIREWALL_PROTECTION_URL', true );
define('PHP_FIREWALL_PROTECTION_REQUEST_SERVER', true );
define('PHP_FIREWALL_PROTECTION_SANTY', true );
define('PHP_FIREWALL_PROTECTION_BOTS', true );
define('PHP_FIREWALL_PROTECTION_REQUEST_METHOD', true );
define('PHP_FIREWALL_PROTECTION_DOS', true );
define('PHP_FIREWALL_PROTECTION_UNION_SQL', true );
define('PHP_FIREWALL_PROTECTION_CLICK_ATTACK', true );
define('PHP_FIREWALL_PROTECTION_XSS_ATTACK', true );
define('PHP_FIREWALL_PROTECTION_COOKIES', false );
define('PHP_FIREWALL_PROTECTION_POST', false );
define('PHP_FIREWALL_PROTECTION_GET', false );
define('PHP_FIREWALL_PROTECTION_SERVER_OVH', true );
define('PHP_FIREWALL_PROTECTION_SERVER_KIMSUFI', true );
define('PHP_FIREWALL_PROTECTION_SERVER_DEDIBOX', true );
define('PHP_FIREWALL_PROTECTION_SERVER_DIGICUBE', true );
define('PHP_FIREWALL_PROTECTION_SERVER_OVH_BY_IP', true );
define('PHP_FIREWALL_PROTECTION_SERVER_KIMSUFI_BY_IP', true );
define('PHP_FIREWALL_PROTECTION_SERVER_DEDIBOX_BY_IP', true );
define('PHP_FIREWALL_PROTECTION_SERVER_DIGICUBE_BY_IP', true );
/** end configuration */
/** IPS PROTECTED */
if ( count( $IP_ALLOW ) > 0 ) {
if ( in_array( $_SERVER['REMOTE_ADDR'], $IP_ALLOW ) ) return;
}
/** END IPS PROTECTED */
/** LANGUAGE */
if ( PHP_FIREWALL_LANGUAGE === 'french' ) {
define('_PHPF_PROTECTION_DEDIBOX', 'Protection contre les serveurs DEDIBOX active, cette IP range n\'est pas autorisée !');
define('_PHPF_PROTECTION_DEDIBOX_IP', 'Protection contre les serveurs DEDIBOX active, cette IP range n\'est pas autorisée !');
define('_PHPF_PROTECTION_DIGICUBE', 'Protection contre les serveurs DIGICUBE active, this IP range is not allowed !');
define('_PHPF_PROTECTION_DIGICUBE_IP', 'Protection contre les serveurs DIGICUBE active, cette IP n\'est pas autorisée !');
define('_PHPF_PROTECTION_KIMSUFI', 'Protection contre les serveurs KIMSUFI active, cette IP range n\'est pas autorisée !');
define('_PHPF_PROTECTION_OVH', 'Protection contre les serveurs OVH active, cette IP range n\'est pas autorisée !');
define('_PHPF_PROTECTION_BOTS', 'Attaque Bot détectée ! stop it ...');
define('_PHPF_PROTECTION_CLICK', 'Click attaque détectée ! stop it .....');
define('_PHPF_PROTECTION_DOS', 'Invalide user agent ! Stop it ...');
define('_PHPF_PROTECTION_OTHER_SERVER', 'Poster depuis un autre serveur est interdit !');
define('_PHPF_PROTECTION_REQUEST', 'Méthode de requête interdite ! Stop it ...');
define('_PHPF_PROTECTION_SANTY', 'Attaque Santy detectée ! Stop it ...');
define('_PHPF_PROTECTION_SPAM', 'Protection SPAM IPs active, cette IP range n\'est pas autorisée !');
define('_PHPF_PROTECTION_SPAM_IP', 'Protection SPAM IPs active, cette IP range n\'est pas autorisée !');
define('_PHPF_PROTECTION_UNION', 'Attaque Union détectée ! stop it ......');
define('_PHPF_PROTECTION_URL', 'Protection url active, string non autorisée !');
define('_PHPF_PROTECTION_XSS', 'Attaque XSS détectée ! stop it ...');
} else {
define('_PHPF_PROTECTION_DEDIBOX', 'Protection DEDIBOX Server active, this IP range is not allowed !');
define('_PHPF_PROTECTION_DEDIBOX_IP', 'Protection DEDIBOX Server active, this IP is not allowed !');
define('_PHPF_PROTECTION_DIGICUBE', 'Protection DIGICUBE Server active, this IP range is not allowed !');
define('_PHPF_PROTECTION_DIGICUBE_IP', 'Protection DIGICUBE Server active, this IP is not allowed !');
define('_PHPF_PROTECTION_KIMSUFI', 'Protection KIMSUFI Server active, this IP range is not allowed !');
define('_PHPF_PROTECTION_OVH', 'Protection OVH Server active, this IP range is not allowed !');
define('_PHPF_PROTECTION_BOTS', 'Bot attack detected ! stop it ...');
define('_PHPF_PROTECTION_CLICK', 'Click attack detected ! stop it .....');
define('_PHPF_PROTECTION_DOS', 'Invalid user agent ! Stop it ...');
define('_PHPF_PROTECTION_OTHER_SERVER', 'Posting from another server not allowed !');
define('_PHPF_PROTECTION_REQUEST', 'Invalid request method check ! Stop it ...');
define('_PHPF_PROTECTION_SANTY', 'Attack Santy detected ! Stop it ...');
define('_PHPF_PROTECTION_SPAM', 'Protection SPAM IPs active, this IP range is not allowed !');
define('_PHPF_PROTECTION_SPAM_IP', 'Protection died IPs active, this IP range is not allowed !');
define('_PHPF_PROTECTION_UNION', 'Union attack detected ! stop it ......');
define('_PHPF_PROTECTION_URL', 'Protection url active, string not allowed !');
define('_PHPF_PROTECTION_XSS', 'XSS attack detected ! stop it ...');
}
/** END LANGUAGE*/
if ( PHP_FIREWALL_ACTIVATION === true ) {
FUNCTION PHP_FIREWALL_unset_globals() {
if ( ini_get('register_globals') ) {
$allow = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'GLOBALS' => 1);
foreach ($GLOBALS as $key => $value) {
if ( ! isset( $allow[$key] ) ) unset( $GLOBALS[$key] );
}
}
}
if ( PHP_FIREWALL_PROTECTION_UNSET_GLOBALS === true ) PHP_FIREWALL_unset_globals();
/** fonctions de base */
FUNCTION PHP_FIREWALL_get_env($st_var) {
global $HTTP_SERVER_VARS;
if(isset($_SERVER[$st_var])) {
return strip_tags( $_SERVER[$st_var] );
} elseif(isset($_ENV[$st_var])) {
return strip_tags( $_ENV[$st_var] );
} elseif(isset($HTTP_SERVER_VARS[$st_var])) {
return strip_tags( $HTTP_SERVER_VARS[$st_var] );
} elseif(getenv($st_var)) {
return strip_tags( getenv($st_var) );
} elseif(function_exists('apache_getenv') && apache_getenv($st_var, true)) {
return strip_tags( apache_getenv($st_var, true) );
}
return '';
}
FUNCTION PHP_FIREWALL_get_referer() {
if( PHP_FIREWALL_get_env('HTTP_REFERER') )
return PHP_FIREWALL_get_env('HTTP_REFERER');
return 'no referer';
}
FUNCTION PHP_FIREWALL_get_ip() {
if ( PHP_FIREWALL_get_env('HTTP_X_FORWARDED_FOR') ) {
return PHP_FIREWALL_get_env('HTTP_X_FORWARDED_FOR');
} elseif ( PHP_FIREWALL_get_env('HTTP_CLIENT_IP') ) {
return PHP_FIREWALL_get_env('HTTP_CLIENT_IP');
} else {
return PHP_FIREWALL_get_env('REMOTE_ADDR');
}
}
FUNCTION PHP_FIREWALL_get_user_agent() {
if(PHP_FIREWALL_get_env('HTTP_USER_AGENT'))
return PHP_FIREWALL_get_env('HTTP_USER_AGENT');
return 'none';
}
FUNCTION PHP_FIREWALL_get_query_string() {
if( PHP_FIREWALL_get_env('QUERY_STRING') )
return str_replace('%09', '%20', PHP_FIREWALL_get_env('QUERY_STRING'));
return '';
}
FUNCTION PHP_FIREWALL_get_request_method() {
if(PHP_FIREWALL_get_env('REQUEST_METHOD'))
return PHP_FIREWALL_get_env('REQUEST_METHOD');
return 'none';
}
FUNCTION PHP_FIREWALL_gethostbyaddr() {
if ( PHP_FIREWALL_PROTECTION_SERVER_OVH === true OR PHP_FIREWALL_PROTECTION_SERVER_KIMSUFI === true OR PHP_FIREWALL_PROTECTION_SERVER_DEDIBOX === true OR PHP_FIREWALL_PROTECTION_SERVER_DIGICUBE === true ) {
if ( # empty( $_SESSION['PHP_FIREWALL_gethostbyaddr'] ) ) {
return $_SESSION['PHP_FIREWALL_gethostbyaddr'] = #gethostbyaddr( PHP_FIREWALL_get_ip() );
} else {
return strip_tags( $_SESSION['PHP_FIREWALL_gethostbyaddr'] );
}
}
}
/** bases define */
define('PHP_FIREWALL_GET_QUERY_STRING', strtolower( PHP_FIREWALL_get_query_string() ) );
define('PHP_FIREWALL_USER_AGENT', PHP_FIREWALL_get_user_agent() );
define('PHP_FIREWALL_GET_IP', PHP_FIREWALL_get_ip() );
define('PHP_FIREWALL_GET_HOST', PHP_FIREWALL_gethostbyaddr() );
define('PHP_FIREWALL_GET_REFERER', PHP_FIREWALL_get_referer() );
define('PHP_FIREWALL_GET_REQUEST_METHOD', PHP_FIREWALL_get_request_method() );
define('PHP_FIREWALL_REGEX_UNION','#\w?\s?union\s\w*?\s?(select|all|distinct|insert|update|drop|delete)#is');
FUNCTION PHP_FIREWALL_push_email( $subject, $msg ) {
$headers = "From: PHP Firewall: ".PHP_FIREWALL_ADMIN_MAIL." <".PHP_FIREWALL_ADMIN_MAIL.">\r\n"
."Reply-To: ".PHP_FIREWALL_ADMIN_MAIL."\r\n"
."Priority: urgent\r\n"
."Importance: High\r\n"
."Precedence: special-delivery\r\n"
."Organization: PHP Firewall\r\n"
."MIME-Version: 1.0\r\n"
."Content-Type: text/plain\r\n"
."Content-Transfer-Encoding: 8bit\r\n"
."X-Priority: 1\r\n"
."X-MSMail-Priority: High\r\n"
."X-Mailer: PHP/" . phpversion() ."\r\n"
."X-PHPFirewall: 1.0 by PHPFirewall\r\n"
."Date:" . date("D, d M Y H:s:i") . " +0100\n";
if ( PHP_FIREWALL_ADMIN_MAIL != '' )
#mail( PHP_FIREWALL_ADMIN_MAIL, $subject, $msg, $headers );
}
FUNCTION PHP_FIREWALL_LOGS( $type ) {
$f = fopen( dirname(__FILE__).'/'.PHP_FIREWALL_LOG_FILE.'.txt', 'a');
$msg = date('j-m-Y H:i:s')." | $type | IP: ".PHP_FIREWALL_GET_IP." ] | DNS: ".gethostbyaddr(PHP_FIREWALL_GET_IP)." | Agent: ".PHP_FIREWALL_USER_AGENT." | URL: ".PHP_FIREWALL_REQUEST_URI." | Referer: ".PHP_FIREWALL_GET_REFERER."\n\n";
fputs($f, $msg);
fclose($f);
if ( PHP_FIREWALL_PUSH_MAIL === true ) {
PHP_FIREWALL_push_email( 'Alert PHP Firewall '.strip_tags( $_SERVER['SERVER_NAME'] ) , "PHP Firewall logs of ".strip_tags( $_SERVER['SERVER_NAME'] )."\n".str_replace('|', "\n", $msg ) );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_OVH === true ) {
if ( stristr( PHP_FIREWALL_GET_HOST ,'ovh') ) {
PHP_FIREWALL_LOGS( 'OVH Server list' );
die( _PHPF_PROTECTION_OVH );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_OVH_BY_IP === true ) {
$ip = explode('.', PHP_FIREWALL_GET_IP );
if ( $ip[0].'.'.$ip[1] == '87.98' or $ip[0].'.'.$ip[1] == '91.121' or $ip[0].'.'.$ip[1] == '94.23' or $ip[0].'.'.$ip[1] == '213.186' or $ip[0].'.'.$ip[1] == '213.251' ) {
PHP_FIREWALL_LOGS( 'OVH Server IP' );
die( _PHPF_PROTECTION_OVH );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_KIMSUFI === true ) {
if ( stristr( PHP_FIREWALL_GET_HOST ,'kimsufi') ) {
PHP_FIREWALL_LOGS( 'KIMSUFI Server list' );
die( _PHPF_PROTECTION_KIMSUFI );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_DEDIBOX === true ) {
if ( stristr( PHP_FIREWALL_GET_HOST ,'dedibox') ) {
PHP_FIREWALL_LOGS( 'DEDIBOX Server list' );
die( _PHPF_PROTECTION_DEDIBOX );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_DEDIBOX_BY_IP === true ) {
$ip = explode('.', PHP_FIREWALL_GET_IP );
if ( $ip[0].'.'.$ip[1] == '88.191' ) {
PHP_FIREWALL_LOGS( 'DEDIBOX Server IP' );
die( _PHPF_PROTECTION_DEDIBOX_IP );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_DIGICUBE === true ) {
if ( stristr( PHP_FIREWALL_GET_HOST ,'digicube') ) {
PHP_FIREWALL_LOGS( 'DIGICUBE Server list' );
die( _PHPF_PROTECTION_DIGICUBE );
}
}
if ( PHP_FIREWALL_PROTECTION_SERVER_DIGICUBE_BY_IP === true ) {
$ip = explode('.', PHP_FIREWALL_GET_IP );
if ( $ip[0].'.'.$ip[1] == '95.130' ) {
PHP_FIREWALL_LOGS( 'DIGICUBE Server IP' );
die( _PHPF_PROTECTION_DIGICUBE_IP );
}
}
if ( PHP_FIREWALL_PROTECTION_RANGE_IP_SPAM === true ) {
$ip_array = array('24', '186', '189', '190', '200', '201', '202', '209', '212', '213', '217', '222' );
$range_ip = explode('.', PHP_FIREWALL_GET_IP );
if ( in_array( $range_ip[0], $ip_array ) ) {
PHP_FIREWALL_LOGS( 'IPs Spam list' );
die( _PHPF_PROTECTION_SPAM );
}
}
if ( PHP_FIREWALL_PROTECTION_RANGE_IP_DENY === true ) {
$ip_array = array('0', '1', '2', '5', '10', '14', '23', '27', '31', '36', '37', '39', '42', '46', '49', '50', '100', '101', '102', '103', '104', '105', '106', '107', '114', '172', '176', '177', '179', '181', '185', '192', '223', '224' );
$range_ip = explode('.', PHP_FIREWALL_GET_IP );
if ( in_array( $range_ip[0], $ip_array ) ) {
PHP_FIREWALL_LOGS( 'IPs reserved list' );
die( _PHPF_PROTECTION_SPAM_IP );
}
}
if ( PHP_FIREWALL_PROTECTION_COOKIES === true ) {
$ct_rules = Array('applet', 'base', 'bgsound', 'blink', 'embed', 'expression', 'frame', 'javascript', 'layer', 'link', 'meta', 'object', 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload', 'script', 'style', 'title', 'vbscript', 'xml');
if ( PHP_FIREWALL_PROTECTION_COOKIES === true ) {
foreach($_COOKIE as $value) {
$check = str_replace($ct_rules, '*', $value);
if( $value != $check ) {
PHP_FIREWALL_LOGS( 'Cookie protect' );
unset( $value );
}
}
}
if ( PHP_FIREWALL_PROTECTION_POST === true ) {
foreach( $_POST as $value ) {
$check = str_replace($ct_rules, '*', $value);
if( $value != $check ) {
PHP_FIREWALL_LOGS( 'POST protect' );
unset( $value );
}
}
}
if ( PHP_FIREWALL_PROTECTION_GET === true ) {
foreach( $_GET as $value ) {
$check = str_replace($ct_rules, '*', $value);
if( $value != $check ) {
PHP_FIREWALL_LOGS( 'GET protect' );
unset( $value );
}
}
}
}
/** protection de l'url */
if ( PHP_FIREWALL_PROTECTION_URL === true ) {
$ct_rules = array( 'absolute_path', 'ad_click', 'alert(', 'alert%20', ' and ', 'basepath', 'bash_history', '.bash_history', 'cgi-', 'chmod(', 'chmod%20', '%20chmod', 'chmod=', 'chown%20', 'chgrp%20', 'chown(', '/chown', 'chgrp(', 'chr(', 'chr=', 'chr%20', '%20chr', 'chunked', 'cookie=', 'cmd', 'cmd=', '%20cmd', 'cmd%20', '.conf', 'configdir', 'config.php', 'cp%20', '%20cp', 'cp(', 'diff%20', 'dat?', 'db_mysql.inc', 'document.location', 'document.cookie', 'drop%20', 'echr(', '%20echr', 'echr%20', 'echr=', '}else{', '.eml', 'esystem(', 'esystem%20', '.exe', 'exploit', 'file\://', 'fopen', 'fwrite', '~ftp', 'ftp:', 'ftp.exe', 'getenv', '%20getenv', 'getenv%20', 'getenv(', 'grep%20', '_global', 'global_', 'global[', 'http:', '_globals', 'globals_', 'globals[', 'grep(', 'g\+\+', 'halt%20', '.history', '?hl=', '.htpasswd', 'http_', 'http-equiv', 'http/1.', 'http_php', 'http_user_agent', 'http_host', '&icq', 'if{', 'if%20{', 'img src', 'img%20src', '.inc.php', '.inc', 'insert%20into', 'ISO-8859-1', 'ISO-', 'javascript\://', '.jsp', '.js', 'kill%20', 'kill(', 'killall', '%20like', 'like%20', 'locate%20', 'locate(', 'lsof%20', 'mdir%20', '%20mdir', 'mdir(', 'mcd%20', 'motd%20', 'mrd%20', 'rm%20', '%20mcd', '%20mrd', 'mcd(', 'mrd(', 'mcd=', 'mod_gzip_status', 'modules/', 'mrd=', 'mv%20', 'nc.exe', 'new_password', 'nigga(', '%20nigga', 'nigga%20', '~nobody', 'org.apache', '+outfile+', '%20outfile%20', '*/outfile/*',' outfile ','outfile', 'password=', 'passwd%20', '%20passwd', 'passwd(', 'phpadmin', 'perl%20', '/perl', 'phpbb_root_path','*/phpbb_root_path/*','p0hh', 'ping%20', '.pl', 'powerdown%20', 'rm(', '%20rm', 'rmdir%20', 'mv(', 'rmdir(', 'phpinfo()', '<?php', 'reboot%20', '/robot.txt' , '~root', 'root_path', 'rush=', '%20and%20', '%20xorg%20', '%20rush', 'rush%20', 'secure_site, ok', 'select%20', 'select from', 'select%20from', '_server', 'server_', 'server[', 'server-info', 'server-status', 'servlet', 'sql=', '<script', '<script>', '</script','script>','/script', 'switch{','switch%20{', '.system', 'system(', 'telnet%20', 'traceroute%20', '.txt', 'union%20', '%20union', 'union(', 'union=', 'vi(', 'vi%20', 'wget', 'wget%20', '%20wget', 'wget(', 'window.open', 'wwwacl', ' xor ', 'xp_enumdsn', 'xp_availablemedia', 'xp_filelist', 'xp_cmdshell', '$_request', '$_get', '$request', '$get', '&aim', '/etc/password','/etc/shadow', '/etc/groups', '/etc/gshadow', '/bin/ps', 'uname\x20-a', '/usr/bin/id', '/bin/echo', '/bin/kill', '/bin/', '/chgrp', '/usr/bin', 'bin/python', 'bin/tclsh', 'bin/nasm', '/usr/x11r6/bin/xterm', '/bin/mail', '/etc/passwd', '/home/ftp', '/home/www', '/servlet/con', '?>', '.txt');
$check = str_replace($ct_rules, '*', PHP_FIREWALL_GET_QUERY_STRING );
if( PHP_FIREWALL_GET_QUERY_STRING != $check ) {
PHP_FIREWALL_LOGS( 'URL protect' );
die( _PHPF_PROTECTION_URL );
}
}
/** Posting from other servers in not allowed */
if ( PHP_FIREWALL_PROTECTION_REQUEST_SERVER === true ) {
if ( PHP_FIREWALL_GET_REQUEST_METHOD == 'POST' ) {
if (isset($_SERVER['HTTP_REFERER'])) {
if ( ! stripos( $_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], 0 ) ) {
PHP_FIREWALL_LOGS( 'Posting another server' );
die( _PHPF_PROTECTION_OTHER_SERVER );
}
}
}
}
/** protection contre le vers santy */
if ( PHP_FIREWALL_PROTECTION_SANTY === true ) {
$ct_rules = array('rush','highlight=%','perl','chr(','pillar','visualcoder','sess_');
$check = str_replace($ct_rules, '*', strtolower(PHP_FIREWALL_REQUEST_URI) );
if( strtolower(PHP_FIREWALL_REQUEST_URI) != $check ) {
PHP_FIREWALL_LOGS( 'Santy' );
die( _PHPF_PROTECTION_SANTY );
}
}
/** protection bots */
if ( PHP_FIREWALL_PROTECTION_BOTS === true ) {
$ct_rules = array( '#nonymouse', 'addresses.com', 'ideography.co.uk', 'adsarobot', 'ah-ha', 'aktuelles', 'alexibot', 'almaden', 'amzn_assoc', 'anarchie', 'art-online', 'aspseek', 'assort', 'asterias', 'attach', 'atomz', 'atspider', 'autoemailspider', 'backweb', 'backdoorbot', 'bandit', 'batchftp', 'bdfetch', 'big.brother', 'black.hole', 'blackwidow', 'blowfish', 'bmclient', 'boston project', 'botalot', 'bravobrian', 'buddy', 'bullseye', 'bumblebee ', 'builtbottough', 'bunnyslippers', 'capture', 'cegbfeieh', 'cherrypicker', 'cheesebot', 'chinaclaw', 'cicc', 'civa', 'clipping', 'collage', 'collector', 'copyrightcheck', 'cosmos', 'crescent', 'custo', 'cyberalert', 'deweb', 'diagem', 'digger', 'digimarc', 'diibot', 'directupdate', 'disco', 'dittospyder', 'download accelerator', 'download demon', 'download wonder', 'downloader', 'drip', 'dsurf', 'dts agent', 'dts.agent', 'easydl', 'ecatch', 'echo extense', 'efp#gmx.net', 'eirgrabber', 'elitesys', 'emailsiphon', 'emailwolf', 'envidiosos', 'erocrawler', 'esirover', 'express webpictures', 'extrac', 'eyenetie', 'fastlwspider', 'favorg', 'favorites sweeper', 'fezhead', 'filehound', 'filepack.superbr.org', 'flashget', 'flickbot', 'fluffy', 'frontpage', 'foobot', 'galaxyBot', 'generic', 'getbot ', 'getleft', 'getright', 'getsmart', 'geturl', 'getweb', 'gigabaz', 'girafabot', 'go-ahead-got-it', 'go!zilla', 'gornker', 'grabber', 'grabnet', 'grafula', 'green research', 'harvest', 'havindex', 'hhjhj#yahoo', 'hloader', 'hmview', 'homepagesearch', 'htmlparser', 'hulud', 'http agent', 'httpconnect', 'httpdown', 'http generic', 'httplib', 'httrack', 'humanlinks', 'ia_archiver', 'iaea', 'ibm_planetwide', 'image stripper', 'image sucker', 'imagefetch', 'incywincy', 'indy', 'infonavirobot', 'informant', 'interget', 'internet explore', 'infospiders', 'internet ninja', 'internetlinkagent', 'interneteseer.com', 'ipiumbot', 'iria', 'irvine', 'jbh', 'jeeves', 'jennybot', 'jetcar', 'joc web spider', 'jpeg hunt', 'justview', 'kapere', 'kdd explorer', 'kenjin.spider', 'keyword.density', 'kwebget', 'lachesis', 'larbin', 'laurion(dot)com', 'leechftp', 'lexibot', 'lftp', 'libweb', 'links aromatized', 'linkscan', 'link*sleuth', 'linkwalker', 'libwww', 'lightningdownload', 'likse', 'lwp','mac finder', 'mag-net', 'magnet', 'marcopolo', 'mass', 'mata.hari', 'mcspider', 'memoweb', 'microsoft url control', 'microsoft.url', 'midown', 'miixpc', 'minibot', 'mirror', 'missigua', 'mister.pix', 'mmmtocrawl', 'moget', 'mozilla/2', 'mozilla/3.mozilla/2.01', 'mozilla.*newt', 'multithreaddb', 'munky', 'msproxy', 'nationaldirectory', 'naverrobot', 'navroad', 'nearsite', 'netants', 'netcarta', 'netcraft', 'netfactual', 'netmechanic', 'netprospector', 'netresearchserver', 'netspider', 'net vampire', 'newt', 'netzip', 'nicerspro', 'npbot', 'octopus', 'offline.explorer', 'offline explorer', 'offline navigator', 'opaL', 'openfind', 'opentextsitecrawler', 'orangebot', 'packrat', 'papa foto', 'pagegrabber', 'pavuk', 'pbwf', 'pcbrowser', 'personapilot', 'pingalink', 'pockey', 'program shareware', 'propowerbot/2.14', 'prowebwalker', 'proxy', 'psbot', 'psurf', 'puf', 'pushsite', 'pump', 'qrva', 'quepasacreep', 'queryn.metasearch', 'realdownload', 'reaper', 'recorder', 'reget', 'replacer', 'repomonkey', 'rma', 'robozilla', 'rover', 'rpt-httpclient', 'rsync', 'rush=', 'searchexpress', 'searchhippo', 'searchterms.it', 'second street research', 'seeker', 'shai', 'sitecheck', 'sitemapper', 'sitesnagger', 'slysearch', 'smartdownload', 'snagger', 'spacebison', 'spankbot', 'spanner', 'spegla', 'spiderbot', 'spiderengine', 'sqworm', 'ssearcher100', 'star downloader', 'stripper', 'sucker', 'superbot', 'surfwalker', 'superhttp', 'surfbot', 'surveybot', 'suzuran', 'sweeper', 'szukacz/1.4', 'tarspider', 'takeout', 'teleport', 'telesoft', 'templeton', 'the.intraformant', 'thenomad', 'tighttwatbot', 'titan', 'tocrawl/urldispatcher','toolpak', 'traffixer', 'true_robot', 'turingos', 'turnitinbot', 'tv33_mercator', 'uiowacrawler', 'urldispatcherlll', 'url_spider_pro', 'urly.warning ', 'utilmind', 'vacuum', 'vagabondo', 'vayala', 'vci', 'visualcoders', 'visibilitygap', 'vobsub', 'voideye', 'vspider', 'w3mir', 'webauto', 'webbandit', 'web.by.mail', 'webcapture', 'webcatcher', 'webclipping', 'webcollage', 'webcopier', 'webcopy', 'webcraft#bea', 'web data extractor', 'webdav', 'webdevil', 'webdownloader', 'webdup', 'webenhancer', 'webfetch', 'webgo', 'webhook', 'web.image.collector', 'web image collector', 'webinator', 'webleacher', 'webmasters', 'webmasterworldforumbot', 'webminer', 'webmirror', 'webmole', 'webreaper', 'websauger', 'websaver', 'website.quester', 'website quester', 'websnake', 'websucker', 'web sucker', 'webster', 'webreaper', 'webstripper', 'webvac', 'webwalk', 'webweasel', 'webzip', 'wget', 'widow', 'wisebot', 'whizbang', 'whostalking', 'wonder', 'wumpus', 'wweb', 'www-collector-e', 'wwwoffle', 'wysigot', 'xaldon', 'xenu', 'xget', 'x-tractor', 'zeus' );
$check = str_replace($ct_rules, '*', strtolower(PHP_FIREWALL_USER_AGENT) );
if( strtolower(PHP_FIREWALL_USER_AGENT) != $check ) {
PHP_FIREWALL_LOGS( 'Bots attack' );
die( _PHPF_PROTECTION_BOTS );
}
}
/** Invalid request method check */
if ( PHP_FIREWALL_PROTECTION_REQUEST_METHOD === true ) {
if(strtolower(PHP_FIREWALL_GET_REQUEST_METHOD)!='get' AND strtolower(PHP_FIREWALL_GET_REQUEST_METHOD)!='head' AND strtolower(PHP_FIREWALL_GET_REQUEST_METHOD)!='post' AND strtolower(PHP_FIREWALL_GET_REQUEST_METHOD)!='put') {
PHP_FIREWALL_LOGS( 'Invalid request' );
die( _PHPF_PROTECTION_REQUEST );
}
}
/** protection dos attaque */
if ( PHP_FIREWALL_PROTECTION_DOS === true ) {
if ( !defined('PHP_FIREWALL_USER_AGENT') || PHP_FIREWALL_USER_AGENT == '-' ) {
PHP_FIREWALL_LOGS( 'Dos attack' );
die( _PHPF_PROTECTION_DOS );
}
}
/** protection union sql attaque */
if ( PHP_FIREWALL_PROTECTION_UNION_SQL === true ) {
$stop = 0;
$ct_rules = array( '*/from/*', '*/insert/*', '+into+', '%20into%20', '*/into/*', ' into ', 'into', '*/limit/*', 'not123exists*', '*/radminsuper/*', '*/select/*', '+select+', '%20select%20', ' select ', '+union+', '%20union%20', '*/union/*', ' union ', '*/update/*', '*/where/*' );
$check = str_replace($ct_rules, '*', PHP_FIREWALL_GET_QUERY_STRING );
if( PHP_FIREWALL_GET_QUERY_STRING != $check ) $stop++;
if (preg_match(PHP_FIREWALL_REGEX_UNION, PHP_FIREWALL_GET_QUERY_STRING)) $stop++;
if (preg_match('/([OdWo5NIbpuU4V2iJT0n]{5}) /', rawurldecode( PHP_FIREWALL_GET_QUERY_STRING ))) $stop++;
if (strstr(rawurldecode( PHP_FIREWALL_GET_QUERY_STRING ) ,'*')) $stop++;
if ( !empty( $stop ) ) {
PHP_FIREWALL_LOGS( 'Union attack' );
die( _PHPF_PROTECTION_UNION );
}
}
/** protection click attack */
if ( PHP_FIREWALL_PROTECTION_CLICK_ATTACK === true ) {
$ct_rules = array( '/*', 'c2nyaxb0', '/*' );
if( PHP_FIREWALL_GET_QUERY_STRING != str_replace($ct_rules, '*', PHP_FIREWALL_GET_QUERY_STRING ) ) {
PHP_FIREWALL_LOGS( 'Click attack' );
die( _PHPF_PROTECTION_CLICK );
}
}
/** protection XSS attack */
if ( PHP_FIREWALL_PROTECTION_XSS_ATTACK === true ) {
$ct_rules = array( 'http\:\/\/', 'https\:\/\/', 'cmd=', '&cmd', 'exec', 'concat', './', '../', 'http:', 'h%20ttp:', 'ht%20tp:', 'htt%20p:', 'http%20:', 'https:', 'h%20ttps:', 'ht%20tps:', 'htt%20ps:', 'http%20s:', 'https%20:', 'ftp:', 'f%20tp:', 'ft%20p:', 'ftp%20:', 'ftps:', 'f%20tps:', 'ft%20ps:', 'ftp%20s:', 'ftps%20:', '.php?url=' );
$check = str_replace($ct_rules, '*', PHP_FIREWALL_GET_QUERY_STRING );
if( PHP_FIREWALL_GET_QUERY_STRING != $check ) {
PHP_FIREWALL_LOGS( 'XSS attack' );
die( _PHPF_PROTECTION_XSS );
}
}
}

Resources