A full-scale PHP 5.3.2+ sandbox class that utilizes PHPParser to prevent sandboxed code from running unsafe code.

Overview

PHPSandbox

##DEPRECATED: The PHPSandbox project has transfered to Corveda/PHPSandbox and will be actively maintained there. This branch is no longer being actively maintained. Update your dependencies as follows:

{
    "require": {
        "corveda/php-sandbox": "2.*"
    }
}

##A full-scale PHP 5.3.2+ sandbox class that utilizes PHP-Parser to prevent sandboxed code from running unsafe code.

It also utilizes FunctionParser to disassemble callables passed to the sandbox, so that PHP callables can also be run in sandboxes without first converting them into strings.

Manual: http://manual.phpsandbox.org

Online API Documentation: http://docs.phpsandbox.org

Build Status Latest Stable Version Total Downloads Latest Unstable Version License Dependency Status

##Features:

  • Finegrained whitelisting and blacklisting, with sensible defaults configured.
  • Includes dynamic demonstration system that allows for local testing of custom sandbox configurations
  • Can redefine internal PHP and other functions to make them more secure for sandbox usage.
  • Can redefine superglobals and magic constants to expose your own values to sandboxed code.
  • Can overwrite the get_defined_* and get_declared_* functions to show only allowed functions, classes, etc. to the sandboxed code.
  • Can selectively allow and disallow function creation, class declarations, constant definitions, keywords, and much more.
  • Can prepend and append trusted code to setup and tear down the sandbox, and automatically whitelist the classes, functions, variables, etc. they define for the sandbox.
  • Can retrieve the generated sandbox code for later usage.
  • Can pass arguments directly to the sandboxed code through the execute method to reveal chosen outside variables to the sandbox.
  • Can access the parsed, prepared and generated code ASTs for further analysis or for serialization.
  • Can define custom validation functions for fine-grained control of every element of the sandbox.
  • Can specify a custom error handler to intercept PHP errors and handle them with custom logic.
  • Can specify a custom exception handler to intercept thrown exceptions and handle them with custom logic.
  • Can specify a validation error handler to intercept thrown validation errors and handle them with custom logic.
  • Can intercept callbacks and validate them against function whitelists and blacklists, even if they are called as strings

##Example usage:

function test($string){
    return 'Hello ' . $string;
}

$sandbox = new PHPSandbox\PHPSandbox;
$sandbox->whitelist_func('test');
$result = $sandbox->execute(function(){
    return test('world');
});

var_dump($result);  //Hello world

##Custom validation example:

function custom_func(){
    echo 'I am valid!';
}

$sandbox = new PHPSandbox\PHPSandbox;
//this will mark any function valid that begins with "custom_"
$sandbox->set_func_validator(function($function_name, PHPSandbox\PHPSandbox $sandbox){
    return (substr($function_name, 0, 7) == 'custom_');  //return true if function is valid, false otherwise
});
$sandbox->execute(function(){
    custom_func();
});
//echoes "I am valid!"

##Custom validation error handler example:

$sandbox = new PHPSandbox\PHPSandbox;
//this will intercept parser validation errors and quietly exit, otherwise it will throw the validation error
$sandbox->set_validation_error_handler(function(PHPSandbox\Error $error, PHPSandbox\PHPSandbox $sandbox){
    if($error->getCode() == PHPSandbox\Error::PARSER_ERROR){ //PARSER_ERROR == 1
        exit;
    }
    throw $error;
});
$sandbox->execute('<?php i am malformed PHP code; ?>');
//does nothing

##Disable validation example:

$sandbox = new PHPSandbox\PHPSandbox;
//this will disable function validation
$sandbox->set_option('validate_functions', false); // or $sandbox->validate_functions = false;
$sandbox->execute('<?php echo system("ping google.com"); ?>');
//Pinging google.com. . .

##Requirements

  • PHP 5.3.2+
  • PHP-Parser
  • FunctionParser (if you wish to use closures)
  • PHP should be compiled with --enable-tokenizer option (it typically is)

##Installation

To install using composer, simply add the following to your composer.json file in the root of your project:

{
    "minimum-stability": "dev",
    "require": {
        "fieryprophet/php-sandbox": "1.3.*"
    }
}

Then run composer install --dry-run to check for any potential problems, and composer install to install.

##LICENSE

Copyright (c) 2013-2015 by Elijah Horton (fieryprophet [at] yahoo.com)

Some rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * The names of the contributors may not be used to endorse or
      promote products derived from this software without specific
      prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Comments
  • Laravel 5?

    Laravel 5?

    I stumbled upon this library and wanted to test it out with my new project which will have some user supplied code executed. But the thing is, this is my first Laravel project and I'm complete newb with both Laravel and composer. I tried running composer require fieryprophet/php-sandbox and I get this:

    d:\wwwroot\my-test-project>composer require fieryprophet/php-sandbox
    Using version ^1.3 for fieryprophet/php-sandbox
    ./composer.json has been updated
    > php artisan clear-compiled
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Installation request for nikic/php-parser == 1.4.0.0 -> satisfiable by nik
    ic/php-parser[v1.4.0].
        - fieryprophet/php-sandbox v1.3.9 requires jeremeamia/functionparser dev-mas
    ter -> no matching package found.
        - fieryprophet/php-sandbox v1.3.8 requires jeremeamia/functionparser dev-mas
    ter -> no matching package found.
        - fieryprophet/php-sandbox v1.3.7 requires jeremeamia/functionparser dev-mas
    ter -> no matching package found.
        - fieryprophet/php-sandbox v1.3.6 requires jeremeamia/functionparser dev-mas
    ter -> no matching package found.
        - fieryprophet/php-sandbox v1.3.5 requires jeremeamia/functionparser dev-mas
    ter -> no matching package found.
        - fieryprophet/php-sandbox v1.3.10 requires nikic/php-parser ~0.9.5 -> satis
    fiable by nikic/php-parser[v0.9.5].
        - fieryprophet/php-sandbox v1.3.11 requires nikic/php-parser ~0.9.5 -> satis
    fiable by nikic/php-parser[v0.9.5].
        - Conclusion: don't install nikic/php-parser v0.9.5
        - Installation request for fieryprophet/php-sandbox ^1.3 -> satisfiable by f
    ieryprophet/php-sandbox[v1.3.10, v1.3.11, v1.3.5, v1.3.6, v1.3.7, v1.3.8, v1.3.9
    ].
    
    Potential causes:
     - A typo in the package name
     - The package is not available in a stable-enough version according to your min
    imum-stability setting
       see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> f
    or more details.
    
    Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further commo
    n problems.
    
    Installation failed, reverting ./composer.json to its original content.
    

    It seems Laravel already uses nikic/php-parser v.1.4.0.0 and your library requires v.0.9.5. Any idea how to solve this?

    opened by avramovic 8
  • Fix references error in PHP 5.6

    Fix references error in PHP 5.6

    Hello guys As you remember I was waiting for #19 pull request and it does not fix the problem with PHP 5.6. Here is my fix. And some updates of requirements. Tests are passed even on 5.6 version Thank you

    P.S. If you accept this pull request, please, do not forget the create new tag (version, release).

    opened by digitalcrab 8
  • Ability for to use functions that you defined in the code.

    Ability for to use functions that you defined in the code.

    When you try to run the code below with the PHPSanbox:

    function test(){
      echo('Hello World!');
    }
    
    function hello(){
      test();
    }
    

    It gives out an error:

    exception 'PHPSandbox\Error' with message 'Sandboxed code attempted to call non-whitelisted function: test'

    This is my sandbox setup:

      $sandbox = new \PHPSandbox\PHPSandbox;
      $sandbox->set_option('allow_trusted_code', true);
      $sandbox->set_option('allow_functions', true);
      $sandbox->set_option('allow_globals', true);
      $sandbox->set_option('allow_variables', true);
      $sandbox->set_option('allow_classes', true);
      $sandbox->set_option('allow_closures', true);
      $sandbox->set_option('allow_namespaces', true);
      $sandbox->set_option('allow_aliases', true);
      $sandbox->set_option('allow_interfaces', true);
      $sandbox->set_option('allow_generators', true);
      $sandbox->set_option('allow_escaping', true);
      $sandbox->set_option('allow_casting', true);
    

    Is there a setup to make the code above work? Or any workarounds?

    opened by iamademar 8
  • Using functions / classes before they are defined

    Using functions / classes before they are defined

    Hi,

    if I try to run the following code in the Sandbox, it will report that function it() was undefined in the eval()'d code:

    If I declare function it() before calling it, the code will execute. Outside the Sandbox, the code shown above runs fine. Is there any way to use the Sandbox with code that uses functions or classes that will be declared after they're referenced in the code?

    Here's my configuration:

    $sandbox->whitelist_keyword(array("type","function","class","echo","new","implements")); $sandbox->set_option("allow_functions",true); $sandbox->set_option("allow_classes",true); $sandbox->set_option("oOverwrite_defined_functions",false);

    Thanks a lot

    Paul

    opened by Paul-Pech 4
  • Whitelist configuration

    Whitelist configuration

    Hello,

    I don't know if this is actually an issue, is more of a question. I see that by default I have to whitelisted everything that I want to be used, but given the situation that I'm trying to use PHPSandbox, this is impossible to be done. It's possible to use without having to set all the functions, vars, keywords, etc to the whitelist? I'd like that things that aren't whitelisted and blacklisted could be executed. Is there a configuration that can be set or there's no possibility to do that?

    Thanks for the attention.

    opened by elisoff 4
  • Have to define function before the calling it

    Have to define function before the calling it

    Here the scenario

    Below will work

    http://kodeinfo.com/sandbox/get/11

    But If you call a function before its defined it wont work

    http://kodeinfo.com/sandbox/get/12

    I have checked the logs and below is what i see problem is execute statement is wrapped in try catch

        try {
            $result = $sandbox->execute($input);
        }catch(Exception $e){
            return $e->getMessage();
        }catch(\Symfony\Component\Debug\Exception\FatalErrorException $e){
            return $e->getMessage();
        }
    

    but it is unable to even execute catch

    below is log

    Call to undefined function print_nice()

    vendor/fieryprophet/php-sandbox/src/PHPSandbox.php(6919) : eval()'d code:3 handleShutdown [internal]:0 [main]

    I am looking into it , thought to just put here if any one can get it right

    Thanks

    opened by shellprog 3
  • Namespace case sensitivity issue in linux

    Namespace case sensitivity issue in linux

    Hi, I have a problem with namespaces on a linux platform with Symfony2. Symfony uses an autoloader that relies on namespace definition for finding the appropiate class declarations. For example, if a class is declared con Foo\Bar namespace, the autoloader loads a class from Foo/Bar directory. When trying to use sandbox in this context, I faced a problem because the namespaces are converted to lowercase, and the autoloader can't find the whitelisted classes.

    For example:

    in Foo/Bar folder: Sample.php:

    namespace Foo\Bar;
    
    class Sample {
        public function doSomething() {
            return 10;
        }
    }
    

    In Test folder:

    namespace Test;
    
     class SampleTest {
          public function test() {
                 $sandbox = \PHPSandbox\PHPSandbox::create();
                 $sandbox->allow_classes = true;         
                 $sandbox->define_alias('Foo\Bar', 'Scripting');
                 $sandbox->whitelist_class('Scripting\Sample');
    
                  $sandbox->execute('
                               class ConcreteSample extends Scripting\Sample {
                                          public function doSomething() {
                                                  return 20;
                                          }
                               }
    
                              $a = new ConcreteSample();
                              return $a->doSomething();
                   ');
          }
     }
    

    With following code:

    $a = new SampleTest();
    $a->test();
    

    I receive an error because the class foo\bar\Sample is not declared. This is because (in linux) the folder foo\bar (lowercase) does not exists.

    Is there a solution to this problem? Why are the namespaces being "normalized"?

    opened by gcaseres 3
  • How to carry a context through repeated executions

    How to carry a context through repeated executions

    Hi, I can't find an answer to this anywhere in the docs: how to pass a context through repeat executions of different sandboxed code.

    For example, on first execution, I define a variable:

    $a = 'hello world';
    

    Then on second execution, I echo it:

    echo $a;
    

    The sandbox appears to discard the context between executions. Is there a way to tell it to save the state so the second execution does not fail with Undefined variable: a?

    opened by datashaman 2
  • Is it possible to parse PHP with html?

    Is it possible to parse PHP with html?

    Is it possible to parse something like this:

    I love eating <?php echo "appples"; ?>

    I'm building a learning tool for my students and while parsing PHP works out fine, I'm trying to figure out how to parse HTML mixed with php

    opened by iamgoodbytes 2
  • http://www.fieryprophet.com/phpsandbox Down

    http://www.fieryprophet.com/phpsandbox Down

    At the moment the site seems to be down so I can't access the manual and I don't see any mention of it here on GitHub so I wasn't sure if you were aware. I see the package comes with the Manual.html though so I guess this is more of a friendly poke then a real issue.

    opened by ISaidHey 2
  • Can the sandbox return detail parse err msg in cluded file

    Can the sandbox return detail parse err msg in cluded file

    Hi,If the sandbox execute function include a file,and the included file has a parse error,now it will return an error with msg "Could not parse sandboxed code!",can it return an error with the real error message? For example: ... $sandbox->execute(function(){ include "test.php"; }); ... and the test.php is like: ... echo "test"; invalid_str_here ...

    could it return some error like: "Parse error: syntax error, unexpected 'echo' (T_ECHO) in sandboxed_code.php on line 4." rather than "could not parse sandboxed code!"?

    Thank you!

    opened by alexwenbj 2
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 0
Releases(v1.3.11)
PHP Static Analysis Tool - discover bugs in your code without running it!

PHPStan - PHP Static Analysis Tool PHPStan focuses on finding errors in your code without actually running it. It catches whole classes of bugs even b

PHPStan 11.6k Dec 30, 2022
TypeResolver - A PSR-5 based resolver of Class names, Types and Structural Element Names

TypeResolver and FqsenResolver The specification on types in DocBlocks (PSR-5) describes various keywords and special constructs but also how to stati

phpDocumentor 9k Dec 29, 2022
Library for counting the lines of code in PHP source code

sebastian/lines-of-code Library for counting the lines of code in PHP source code. Installation You can add this library as a local, per-project depen

Sebastian Bergmann 715 Jan 5, 2023
Provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths

sebastian/environment This component provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths. Instal

Sebastian Bergmann 6.5k Jan 3, 2023
Search PHP source code for function & method calls, variables, and more from PHP.

Searching PHP source code made easy Search PHP source code for function & method calls, variable assignments, classes and more directly from PHP. Inst

Permafrost Software 22 Nov 24, 2022
A PHP code-quality tool

GrumPHP Sick and tired of defending code quality over and over again? GrumPHP will do it for you! This composer plugin will register some git hooks in

PHPro 3.9k Jan 1, 2023
Copy/Paste Detector (CPD) for PHP code.

PHP Copy/Paste Detector (PHPCPD) phpcpd is a Copy/Paste Detector (CPD) for PHP code. Installation This tool is distributed as a PHP Archive (PHAR): $

Sebastian Bergmann 2.2k Jan 1, 2023
Analyze PHP code with one command

PHPQA Analyze PHP code with one command. Requirements PHP >= 5.4.0 xsl extension for HTML reports Why? Every analyzer has different arguments and opti

edgedesign/phpqa 542 Dec 24, 2022
Performs advanced static analysis on PHP code

PHP Analyzer Please report bugs or feature requests via our website support system ? in bottom right or by emailing [email protected]. Contri

Continuous Inspection 443 Sep 23, 2022
A static php code analysis tool using the Graph Theory

Mondrian Ok guyz, you have a master degree in Graph Theory, you follow Law of Demeter and you live on S.O.L.I.D principles ? Let's have some Fun ! (^ω

Florent Genette 391 Nov 30, 2022
Instant Upgrades and Instant Refactoring of any PHP 5.3+ code

Rector - Speedup Your PHP Development Rector helps you with 2 areas - major code changes and in daily work. Do you have a legacy code base? Do you wan

RectorPHP 6.5k Jan 8, 2023
Deptrac is a static code analysis tool for PHP that helps you communicate, visualize and enforce architectural decisions in your projects

Deptrac is a static code analysis tool for PHP that helps you communicate, visualize and enforce architectural decisions in your projects. You can freely define your architectural layers over classes and which rules should apply to them.

QOSSMIC GmbH 2.2k Dec 30, 2022
phpcs-security-audit is a set of PHP_CodeSniffer rules that finds vulnerabilities and weaknesses related to security in PHP code

phpcs-security-audit v3 About phpcs-security-audit is a set of PHP_CodeSniffer rules that finds vulnerabilities and weaknesses related to security in

Floe design + technologies 655 Jan 3, 2023
A tool to automatically fix PHP Coding Standards issues by Dragon Code.

A tool to automatically fix PHP Coding Standards issues by Dragon Code.

The Dragon Code 24 Aug 27, 2022
PHP code scanner to use with gettext/gettext

PHP code scanner to use with gettext/gettext

Gettext 12 Nov 11, 2022
Code Climate CLI

Code Climate CLI Overview codeclimate is a command line interface for the Code Climate analysis platform. It allows you to run Code Climate engines on

Code Climate 2.4k Dec 26, 2022
Static code analysis to find violations in a dependency graph

PhpDependencyAnalysis PhpDependencyAnalysis is an extendable static code analysis for object-oriented PHP-Projects to generate dependency graphs from

Marco Muths 546 Dec 7, 2022
Automagically generate UML diagrams of your Laravel code.

Laravel UML Diagram Generator Automagically generate UML diagrams of your Laravel code. Installation To install LTU via composer, run the command: com

Andy Abi Haidar 93 Jan 1, 2023
The Stopwatch component provides a way to profile code.

Stopwatch Component The Stopwatch component provides a way to profile code.

Symfony 2.6k Dec 28, 2022