how to write a simple PHP fiddle to execute php code safely - php

I want to write a simple PHP fiddle for a programming tutorials website
Similar to Code Academy website
Example
Code Academy PHP Fiddle Example
I thought of using Code Mirror as a text editor
But How I could execute the PHP Code that the user write safely ??
I tried to use file_put_contents() and file_get_contents in their editor
And it works :) is it safe !!
I can't use extensions like runkit
because I am on a shared hosting :(

Short answer: You can't. You need a sandbox of some sort, which will take far more systems access than you'll get on shared hosting. You would need to set up your own host with your own sandboxed PHP executables in order to achieve this.
As you have it there, it is absolutely not safe.

I think the safest way is to edit PHP sources and remove the most dangerous functions, compile this and run this new PHP environment from the real PHP.
Parsing the user input and sending to eval is in my opinion a security hole. You wouldn't be able to detect dangerous statements like
$a = 'ma';
$a .= 'il';
{$a}(...);
etc.

Related

Virus file systems.php on my server?

I found a file systems.php on my webserver that neither I - as user - placed there, nor my webserver provider has placed in there. I viewed the file, it only contains one preg_replace() statement with an extremly long $replacement part, which seems to be somehow encoded.
preg_replace("/.*/e","\x28\x65\...\x29\x29\x3B",".");
If I interpret this statement correctly, it would mean that basically everything shall be replaced be the $replacement part (which might be encrypted/encoded virus injection stuff).
I have uploaded the whole code as pastebin here. Someone has an idea in what way the code is encrypted/how it can be decrypted in order to assess the grade of compromisation of my server?
Update
This might be the attack vector:
So after some digging, we found that this script was planted using a vulnerability in the Uploadify jQuery library. The library's existence was discovered by the attacker through google. source
Unhexxing the shellcode shows it's executing eval(gzinflate(base64_decode(huge string));
I changed this eval to an echo and the full output is on pastebin here:
http://pastebin.com/t1iZ5LQ8
I haven't looked much further into this but it certainly seems dodgy. Just thought I'd do some of the legwork for anyone interested in looking at it further
EDIT
Little bit more detailed look, it appears to allow an attacker to upload files to your server, and take a dump of any databases on the box
It's look like a Shellcode, which can be disastrous for your server, shellcode executed by the CPU can give access to a shell or shuch of things.
For more informations about shellcodes here's a good article :
http://www.vividmachines.com/shellcode/shellcode.html
This upload may hide a possible exploit on your server which grant access to upload or write data into, try to check your logs to identify the problem.

encrypt a part of source code

I have a php file. I just want to protect a few line in it. So I need to encrypt file but I still want it works like a normal php file. Which software/tool should I use now? Can you give me an advice.
I want something like this
<?php
...
normal code
...
encrypted code (Dfhjkllasjdoasd)
...
normal code
?>
Thank you
You can consider using IonCube, PhpSheild, SourceGuardian.
Looking for free? its can be build into php. check bCompiler
Please note, that these encoded/encrypted file can be included in other files too, so you can have some of your files encoded/encrypted and leave which you don't want to.
for Partial textual encryption & decryption see Best way to use PHP to encrypt and decrypt passwords?
You could consider moving the important bits into a separate file as functions and compiling them into a PHP extension using something like HipHop. It would increase the hassle of installing your software though, so you need to be sure it's worth it.

Execute PHP code with restrictions

We have a CMS editor where php is allowed to be used inside it, however we need to restrict access some commands such as file_get_contents, file(), and global.
Can someone help me with a boolean response regex for that? The text from the template is stored in a string.
I know, probably not an ideal method for this but it's all I can come up with for now :)
What you want to do is pretty much impossible. It is really hard to protect yourself against attacks if you allow people to execute code on your machine.
Here is the try I had on it: Sandbox. Source code.
What it does is basically maintain a large list of blacklisted functions for filesystem access, shell access, a.s.o (I allowed some functions for reading the filesystem like show_source that should not be allowed if you want to use it for something real.)
It also tries to protect from more hidden attacks like $func = 'unlink'; $func(__FILE__); by turning it into $func = 'unlink'; ${'___xyz'.!$___xyz=Sandbox::checkVarFunction($func)}(__FILE__) a.s.o.
PS: Still you probably don't want to allow people to run PHP code on your site. The risk is just by far too big. Instead I would allow people to use a templateing language inside the editor. A good candidate would be Twig, because it has a built in sandbox which allows you to restrict usage to certain tags, functions, ...
It's going to be very hard to protect yourself perfectly.
As I see it, you have a few options:
Search for predefined strings which is not allowed in your content (like file_get_contents) and display a error message saying that the user cannot save because of this. This will however lead to "hacks" where you'll end up searching for all possible characters, like () which can be valid in some cases.
Use token_get_all and try to parse the content as PHP. You can then loop through the whole source code, token by token, and see if you find a token you do not accept.
Write your own language or DSL for this. This language should only be capable of doing exactly what you want. Depending on your requirements, this can be the easiest and most maintainable way to go.
You can use preg_match for this. Use:
if(preg_match("#(file_get_contents|file)\(#i",$text))

Can I execute js files via php?

The situation is next:
I have php file, which parses a web-page. on that web-page is a phone number and it's digits are mixed with each other. The only way to put each digit on the correct place is to use some JS functions (on the client side). So, when I execute that php file in linux console, it gives me all that I need, except js function's result (no wonder - JavaScript is not a server-side language). So all I see from JS - only a code, that I have written.
The question: can I execute js files via php and how?
Results of a quick google search (terms = javascript engine php)
J4P5 -- not developed since 2005 [BAD](according to its News)
PECL package spidermonkey
a 2008 post by jeresig points to PHPJS but can't see when it was last updated.
I'm sure you'll find many more links on that google search.
Alternatively:
you say that the digits are scrambled and you need to "unscramble" them using js. Can you code that unscrambling logic into a PHP function and just use it? Will sure save you a lot of trouble, but if learning to use js in php is what you're after, then its a whole different story...
Zend tutorial: "Using javascript in PHP with PECL and spidermonkey"?
http://en.wikipedia.org/wiki/Comparison_of_Server-side_JavaScript_solutions
Alternatively, PHP has simple functions for executing other programs and retrieving their output (I used this along with GPG once to create a PHP file manager which could live-encrypt files as you were uploading them and live-decrypt as you were downloading them)
Using those functions along with http://code.google.com/p/v8/ you should be able to interpret any javascript.
Not unless you know someone who's implemented a Javascript engine in PHP.
In other words, probably not.
Without some sort of browser emulation or passing the unparsed js off to a server side implementation of javascript (maybe node.js?), you won't be able to execute it.
However, does the page use the same js function to unscramble the phone number every time? You should be able to read the incorrect digits and shuffle them with PHP.
If you're prepared to do a bit of work building your own JS runtime to work with it, Tim Whitlock has written a javascript tokenizer and parser in pure PHP
node.js is server-side... but full JS :) no PHP in it so I don't it answer your needs...
Anyway, here is an example : a chat in JS both client & server-side : http://chat.nodejs.org/
Plus, not every host allows you to use the v8 engine...
If you have Javascript data objects, and you need to convert them to/from PHP arrays, that's quite easy using PHP's json_encode() and json_decode() functions.
But actually running Javascript code? No. You can't. You might be able to find a JS interpreter written in PHP (a few other answers have pointed a links that may or may not help you here), or more likely execute the JS using a stand-alone JS interpreter on your server which you call out to from PHP. However if the JS code includes references to the browser's DOM (which is highly likely), that's a whole other set of issues which will almost certainly make it impossible.
Given the way you describe the question, I'd say the easiest solution for you would just be to re-implement the JS code as PHP code; it's unlikely that all the work arounds being suggested would be appropriate for what sounds like a fairly simple bit of utility code.

Code to parse user agent string?

As strange as I find this, I have not been able to find a good PHP function anywhere which will do an intelligent parse of a user agent string? Googled it for about 20 minutes now.
I have the string already, I just need something that will chop it up and give me at least browser/ver/os.
Know of a good snippet anywhere?
The get_browser() function has been available in PHP for quite a long a time.
The PHP manual is free, can be downloaded in various formats and viewed online (with comments)
https://github.com/browscap/browscap-php - this is a standalone library that aims to replace get_browser function. For shared hostings it seems to be a better option.
Works on: PHP 5
You can try to use: https://github.com/tobie/ua-parser. This is multi-language tool to parsing user agent string. For PHP is here: https://github.com/tobie/ua-parser/tree/master/php
Try out ThaDafinser/UserAgentParser it's an abstraction for many available user agent parsers.
So if you are not happy with one - just switch to another (or combine them)
You can try it out here
There is a PHP class library i found out, and it has worked so well for me. It is in the link below.
https://www.toms-world.org/blog/parseuseragentstring
It is lightweight and just does what I wanted (Browser, Version, OS, Mobile/PC, and much more) in a memory-friendy manner.

Categories