How to secure a template engine in PHP from injection - php

I am currently trying to create a simple template engine in PHP. The main thing I care about is security, however template tutorials do not. Lets say I have a database table with a username and his description. The user can type whatever he wants there.
My guess would be to use htmlspecialchars() function, to prevent javascript and html injection. But what about 'template code injection'? If my template rule is to replace [#key] to "value", the user can update his description that interferes with my template handler. Should I treat "[", "#", "]" as special characters and replace them with their ascii code when using my set method?
template.php:
class Template {
protected $file;
protected $values = array();
public function __construct($file) {
$this->file = $file;
}
public function set($key, $value) {
$this->values[$key] = $value;
}
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
}
example.tpl:
Username: [#name]
About me: [#info]
index.php:
include 'template.php';
$page = new Template('example.tpl');
$page->set('info', '[#name][#name][#name]I just injected some code.');
$page->set('name', 'Tom');
echo $page->output();
This would display:
Username: Tom
About me: TomTomTomI just injected some code.
The code I used is based on:
http://www.broculos.net/2008/03/how-to-make-simple-html-template-engine.html

Change your function to search in the unchanged template only once for the known keys:
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).";
}
$output = file_get_contents($this->file);
$keys = array_keys($this->values);
$pattern = '$\[#(' . implode('|', array_map('preg_quote', $keys)) . ')\]$';
$output = preg_replace_callback($pattern, function($match) {
return $this->values[$match[1]];
}, $output);
return $output;
}

I was thinking about it and I think this solution is fastest and simplest:
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
if (strpos($output, "[#$value]") !== FALSE)
$value = '['.substr($value,1,-1).']';
$output = str_replace($tagToReplace, $value, $output);
}
It replaces brackets in value with html entity string if [$value] is in output.
Used this html entity list
For future adopters:
This kind of solution is OK if Template Parser is implemented by loading non-interpeted/non-evaled file (as is OP's case by loading local file using file_get_contents). However, if it's implemented by INCLUDING PHP view, beware that this check won't handle the case when you put some user-modifiable data from database into view directly (without using parser, e.g. <?=$var;?>) and then use template parser for this view. In that case, parser has no way to know if these data are part of template structure and this check won't work for them. (I don't know how should this case be handled properly.) Anyhow, I think best practice is to never pass sensitive data to template parser, even if you don't use them in your template. When attacker then tricks parser to eval his custom data, he won't get information he didn't already have. Even better, don't use template parser.

Related

Pass multiple parameters to a blade directive

I'm trying to create a blade directive to highlight some words that will return from my search query.
This is my blade directive:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('highlight', function($expression, $string){
$expressionValues = preg_split('/\s+/', $expression);
foreach ($expressionValues as $value) {
$string = str_replace($value, "<b>".$value."</b>", $string);
}
return "<?php echo {$string}; ?>";
});
}
public function register()
{
}
}
And I call in blade like this:
#highlight('ho', 'house')
But, this erros is following me:
Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}()
How to solve it?
For associative arrays, eval() may be the easiest. But its use is adverted as dangerous, because it's like your opening a hole, a needle for code execution. In same time eval() execute at runtime, well it store the code to be executed in database (caching [well it mean it cache compiled byte code]). That's additional overhead, so performance will take a hit. Here's a nice paper on the topic [didn't read or get into the details]) https://link.springer.com/chapter/10.1007%2F978-981-10-3935-5_12.
Well here I may have got you!, there is no performance difference at server serving performance, because views are cached, and generated only when you change them. Directives are translated to php code and in another process they are cached. (you can find the generated view in storage/framework/views)
So for
Blade::directive('custom', function ($expression) {
eval("\$myarray = [$expression];");
// do something with $myarray
return "<?php echo ..";
});
It's just ok. There is nothing to talk about for eval() and performance (it's done and cached, and the generated php code is the one that will run over and over (just make sure the returned php code by the directive doesn't hold eval(), unless there is a reason). Using eval() directly (which will be used for different request over and over) will impact performance.
(I wanted to talk about eval(), I think those are useful info)
as it is we can parse array form ["sometin" => "i should be sting", "" => "", ...].
eval("\$array = $expression;");
// then we can do what we want with $array
However we can't pass variables. ex: #directive(["s" => $var])
if we use eval, $var will be undefined in the directive function scope. (don't forget that directive are just a way to generate tempalte beautifully, and turning the ugly (not really ugly) php code into such directive. In fact it's the inverse, we are turning the beautiful directive to the php code that will be executed at the end. And all you are doing here is generating, building, writing the expression that will form the final php pages or files.)
What you can do instead is to pass the variable in this way
["s" => "$var"] , so it will pass through eval. And then in your return statement, use it example:
return "<?php echo ".$array['s'].";?>";
when the template will be generated this will be <?php echo $var;?>;
Remember, if you decide to use eval, never use it within the returned string! or maybe you want to in some cases.
Another solution
(which is easy) along to the proposed parsing solutions, is to use a json format to passe data to your directive, and just use json_decode. (it just came to me)
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('highlight', function($json_expression){
$myArray = json_decode($json_expression)
// do something with the array
});
}
public function register()
{
}
}
Here an example where I needed to do so:
the goal is to automate this
#php
$logo = !empty($logo) ? $logo : 'logo';
$width = !empty($width) ? $width : 'logo';
//... // wait i will not always keep doing that ! h h
#endphp // imaging we do that for all different number of view components ...
and so I wrote this directive:
public function boot()
{
Blade::directive('varSet', function ($expr) {
$array = json_decode($expr, true);
$p = '<?php ';
foreach ($array as $key => $val) {
if (is_string($val)) {
$p .= "\$$key = isset(\$$key) && !empty(\$$key) ? \$$key : '$val'; ";
} else {
$p .= "\$$key = isset(\$$key) && !empty(\$$key) ? \$$key : $val; ";
}
}
$p .= '?>';
return $p;
});
}
We use it like this:
#varSet({
"logo": "logo",
"width": 78,
"height": 22
})// hi my cool directive. that's slick.
Why this form work? it get passed as a string template like this
"""
{\n
"logo": "logo",\n
"width": 78,\n
"height": 22\n
}
"""
For using in template variable pass them as string like that "$var", same as what we did with eval.
For parsing from ["" => "", ..] format may be eval() is the best choice. Remember that this is done at template generation which are cached later, and not updated, until we make change again. And remember to not use eval() within the return ; directive instruction. (only if your application need that)
for just multi arguments, and so not an array:
A function like that will do the job:
public static function parseMultipleArgs($expression)
{
return collect(explode(',', $expression))->map(function ($item) {
return trim($item);
});
}
or
public static function parseMultipleArgs($expression)
{
$ar = explode(',', $expression);
$l = len($ar);
if($l == 1) return $ar[0];
for($i = 0; $i < $l; $i++){$ar[$i] = trim($ar[$i])}
return $ar;
}
and you can tweak them as you like, using str_replace to remove things like () ...etc [in short we workout our own parsing. RegEx can be helpful. And depend on what we want to achieve.
All the above are way to parse entries and separate them into variables you use for generating the template. And so for making your return statement.
WHAT IF ALL YOU WANT IS TO HAVE YOUR DIRECTIVE TAKE AN ARRAY WITH VARIABLES FROM THE VIEW SCOPE:
like in #section('', ["var" => $varValue])
Well here particulary we use the multi arguments parsing, then we recover ["" => ..] expression separately (and here is not the point).
The point is when you want to pass an array to be used in your code (view scope). You just use it as it is. (it can be confusing).
ex:
Blade::directive("do", function ($expr) {
return "<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter($expr); ?>
});
This will evaluate to
<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter(["name" => $user->name, .......]); ?>
And so all will work all right. I took an example where we use a function, you can put all a logic. Directives are just a way to write view in a more beautiful way. Also it allow for pre-view processing and generation. Quiet nice.
Blade::directive('custom', function ($expression) {
eval("\$params = [$expression];");
list($param1, $param2, $param3) = $params;
// Great coding stuff here
});
and in blade template:
#custom('param1', 'param2', 'param3')
I was searching for this exact solution, then decided to try something different after reading everything and ended up coming up with the solution you and I were both looking for.
No need for JSON workarounds, explodes, associative arrays, etc... unless you want that functionality for something more complex later.
Because Blade is just writing out PHP code to be interpreted later, whatever you've placed into your #highlight directive is the exact PHP code in string format that will be interpreted later.
What to Do:
Make and register a helper function that you can call throughout your application. Then use the helper function in your blade directive.
Helper Definition:
if(!function_exists('highlight')){
function highlight($expression, $string){
$expressionValues = preg_split('/\s+/', $expression);
foreach ($expressionValues as $value) {
$string = str_replace($value, "<b>".$value."</b>", $string);
}
return $string;
}
}
Blade Directive:
Blade::directive('highlight', function ($passedDirectiveString){
return "<?php echo highlight($passedDirectiveString);?>";
});
Usage (Example):
<div>
#highlight('ho', 'house')
</div>
Understanding:
This is equivalent to writing out:
<div>
{! highlight('ho', 'house') !}
</div>
I think you can only pass one parameter. It's not pretty but you could pass your parameters as an array like so:
#highlight(['expression' => 'ho', 'string' => 'house'])
So your directive could be
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('highlight', function($array){
$expressionValues = preg_split('/\s+/', $array['expression']);
foreach ($expressionValues as $value) {
$array['string'] = str_replace($value, "<b>".$value."</b>", $array['string']);
}
return "<?php echo {$array['string']}; ?>";
});
}
public function register()
{
}
}
Found it here: https://laracasts.com/discuss/channels/laravel/how-to-do-this-blade-directive
The best way to accomplish this task is exactly as #Everrett suggested.
I checked through the blade code, and this is exactly how the laravel team has to do it as well.
If you look through vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php, at the compileDd function, you'll notice that they use $arguments instead of $expression like they do in all of the other compile functions found in vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/
// CompilesHelpers.php
protected function compileDd($arguments)
{
return "<?php dd{$arguments}; ?>";
}
//CompilesConditionals.php
protected function compileIf($expression)
{
return "<?php if{$expression}: ?>";
}
And if you look at vendor/symfony/var-dumper/Resources/functions/dump.php you'll see that Laravel handles variable arguments with ... splat notation in the dd function.
if (!function_exists('dd')) {
function dd(...$vars)
{
}}
So you could do a directive like: (I put my custom function in app\helpers)
If you do the same, you need to make sure to escape the backslashes.
Blade::directive('customFunc', function ($expression) {
return "<?php \\App\\Helpers\\customFunc({$arguments}); ?>";
});
and a custom function like:
/**
* Custom function to demonstrate usage
* #param mixed ...$args
* #return void
*/
function customFunc(...$args): void {
// Extract variables //
// Use pad to get expected args, and set unset to null //
list($arg1, $arg2, $arg3) = array_pad($args, 3, null);
// Echo out args //
echo "arg1: ${arg1} | arg2: ${arg2} | arg3: {$arg3}";
}
run php artisan view:clear
And then use the directive:
<div>
#customFunc('hello','wonderful', 'world')
</div>
// Returns:
arg1: hello | arg2: wonderful | arg3: world
// Using
<div>
#customFunc('hello', 'world')
</div>
// Returns:
arg1: hello | arg2: world | arg3:
The best reason to do it this way is so that if your function evolves or changes, you only need to modify the underlining function. You wont have to clear views every time you change the code.
I found an alternative approach to accessing View variables within a Blade Directive.
I wanted to check whether a given string appeared as an array key in a variable accessible in the view scope.
As the Blade Directive returns PHP which is evaluated later, it is possible to 'trick' the Directive by breaking up a variable name so that it doesn't try to parse it.
For example:
Blade::directive('getElementProps', function ($elementID) {
return "<?php
// Reference the $elementData variable
// by splitting its name so it's not parsed here
if (array_key_exists($elementID, $" . "elementData)) {
echo $" . "elementData[$elementID];
}
?>";
});
In this example we have split the $elementData variable name so the Blade Directive treats it like a string. When the concatenated string is returned to the blade it will be evaluated as the variable.
Blade::directive('highlight', function($arguments){
list($arg1, $arg2) = explode(',',str_replace(['(',')',' ', "'"], '', $arguments));
$expressionValues = preg_split('/\s+/', $arg1);
$output = "";
foreach ($expressionValues as $value) {
$output .= str_replace($value, "<b>".$value."</b>", $arg2);
}
return "<?php echo \"{$output}\"; ?>";
});
The value received on blade directive function is a sting, so, you must parse to get the values:
BLADE
#date($date, 'd-M-Y')
AppServiceProvider
Blade::directive('date', function ($str) {
// $str = "$date, 'd-M-Y'";
$data = explode(',',str_replace(' ', '', $str));
//$data = ["$date", "'d-M-Y'"]
$date = $data[0];
$format = $data[1];
return "<?= date_format(date_create($date), $format) ?>";
});
If you want to reference variables within a custom blade directive you may not need to pass them directly to the directive. I solved this problem by calling the blade directive from within a blade component. Blade components have local variable scope and so you can simply pass all the variables you need within the call to the blade component (without polluting your view scope). This is sufficient so long as you don't actually need to modify the variables or use them for control logic in your directive.
//view.blade.php
#component('my-component',['myVar1'=> $something, 'myVar2'=>$somethingElse])
#endcomponent
//my-component.blade.php
#myBladeDirective('Two variables accessible')
//Boot method of relevant service provider
Blade::directive('myBladeDirective', function ($someVar) {
return "<?php echo $someVar : {$myVar1} and {$myVar2};?>
});

how to implement a custom foreach template view method

I was coding a TemplateView Class which is replacing #somevariable# placeholders with it's controller set correspondent. ViewHelpers are called via placeholders that simulate a function like #headerFiles()# for example.
The thing missing is a foreach loop definition like for example the smarty
{foreach from=$var key=index item=value} definition.
Until now I was iterating over a database object inside the controller and having a heredok or string concatenation assigned to the view. So there is a lot of html inside the controllers which I think should not be the controllers job.
I already implemented smarty into the app for testing and it's working fine - But when I decide to really use it I would have to change so many things like all partial templates would have to be .tpl files and all template directories would have to be merged ? or in one place and so on.
So my question is:
Are there any good examples or codesnippets I could use to implement a custom foreach loop method ? Before I have to change everything to use smarty. I also want to avoid using plain php like <?php foreach(): endforeach; ?>
UPDATE:
what concerns would one have going this direction ?
In a template:
#foreach array#
if($key !== 'fart'){
echo $val;
}
#endforeach#
class Foreacher {
private $template;
protected $array = array('fart' => 'poop', 'foo', 'bar');
public function __construct($template){
$this->template = file_get_contents($template);
}
public function parse(){
if(preg_match_all('/#foreach ([\w]+)#(.*?)#endforeach#/is', $this->template, $matches, PREG_SET_ORDER)){
$var = $matches[0][1];
$freach = "<?php foreach(\$this->$var as \$key => \$val){";
$freach .= $matches[0][2];
$freach .= "} ?>";
$parsed = str_replace($matches[0][0], $freach, $this->template);
$this->render($parsed);
}
}
public function __get($var){
if(isset($this->$var)){
return $this->$var;
}
return null;
}
protected function render($string){
$tmp = tmpfile();
fwrite($tmp, $string);
fseek($tmp, 0);
ob_start();
$file = stream_get_meta_data($tmp);
include $file['uri'];
$data = ob_get_clean();
fclose($tmp);
echo $data;
}
}

Remove Codeigniter label wrapping lang()

How do I remove the auto label wrapping that is for the lang() in Codeigniter.
The manual doesn't say anything about it: https://www.codeigniter.com/user_guide/helpers/language_helper.html
Do I have to write a function by myself or is there a simple clean way that Im missing?
Don't write the second parameter. Keep it empty.
Take a look at the lang function (found in: /system/helpers/language_helper.php):
function lang($line, $for = '', $attributes = array())
{
$CI =& get_instance();
$line = $CI->lang->line($line);
if ($for !== '')
{
$line = '<label for="'.$for.'"'._stringify_attributes($attributes).'>'.$line.'</label>';
}
return $line;
}
As you can see it takes 3 parameters. The first parameter is required, but the second two are optional. If you state a second parameter it will return the language string wrapped in a label.
So stating only the first parameter should make it output just the language string.
UPDATE:
From reading your comment it sounds like you would be better off using the language class directly. However the language class alone will not be enough, you will need to extend it for your purpose. To do this you can create a new file in your application/core folder called MY_lang.php.
class MY_Lang extends CI_Lang {
// You want to extend the line function
function line($line = '', $value = '')
{
$line = ($line == '' OR ! isset($this->language[$line])) ? FALSE : $this->language[$line];
// We can assume that if a value is passed it is intended to be inserted into the language string
if($value) {
$line = sprintf($line, $value);
}
// Because killer robots like unicorns!
if ($line === FALSE)
{
log_message('error', 'Could not find the language line "'.$line.'"');
}
return $line ;
}
}
Assuming your language file has a string like so:
$lang['welcome_text'] = "Welcome %s";
You could then use this by loading the language class, and using the following code:
$name = "foo";
$this->lang->line('welcome_text', $name);
The above is 100% untested, so it may need some tweeking, but it should give you somewhere to start from.

php str_replace template with placeholders

I have one array for data
$data = array(title=>'some title', date=>1350498600, story=>'Some story');
I have a template
$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
All i want is to fit data into template and i know that can be done by str_replace but my problem is the date format. date format is coming from the template not from the data, in data date is stored as php date.
yesterday i tried to ask the same question but i think my question wasn't clear.
Anybody please help me.
i think it won't work with str_replace easily so i'm going to use preg_replace
$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
$result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', function ($match) use($data) {
$value = isset($data[$match[1]]) ? $data[$match[1]] : null;
if (!$value) {
// undefined variable in template throw exception or something ...
}
if (! empty($match[2]) && $match[1] == "date") {
$value = date($match[2], $value);
}
return $value;
}, $template);
Instead of using date(m) or date(Y) you could also do things like
date(d-m-Y) using this snippet
This has the disadvantage that you can format only the date variable using this mechanism. But with a few tweaks you can extend this functionality.
Note: If you use a PHP version below 5.3 you can't use closures but you can do the following:
function replace_callback_variables($match) {
global $data; // this is ugly
// same code as above:
$value = isset($data[$match[1]]) ? $data[$match[1]] : null;
if (!$value) {
// undefined variable in template throw exception or something ...
}
if (! empty($match[2]) && $match[1] == "date") {
$value = date($match[2], $value);
}
return $value;
}
$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
// pass the function name as string to preg_replace_callback
$result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', 'replace_callback_variables', $template);
You can find more information about callbacks in PHP here
I'd suggest using a templating engine like so:
https://github.com/cybershade/CSCMS/blob/master/core/classes/class.template.php
And then your templates turn out like this:
https://github.com/cybershade/CSCMS/blob/master/themes/cybershade/site_header.tpl
and
https://github.com/cybershade/CSCMS/blob/master/modules/forum/views/viewIndex/default.tpl
Download this file: http://www.imleeds.com/template.class.txt
Rename the extension to .PHP from .TXT
This is something I created years ago, I keep my HTML away from my PHP, always. So see an example below.
<?php
include("template.class.php");
//Initialise the template class.
$tmpl = new template;
$name = "Richard";
$person = array("Name" => "Richard", "Domain" => "imleeds.com");
/*
On index.html, you can now use: %var.name|Default if not found% and also, extend further, %var.person.Name|Default%
*/
//Output the HTML.
echo $tmpl->run(file_get_contents("html/index.html"));
?>

How to make a php template engine?

I need to make a small and simple php template engine I searched a lot and many of them were too complex to understand and I don't want to use smarty and other similar engines, I have got some idea from Stack Overflow like this:
$template = file_get_contents('file.html');
$array = array('var1' => 'value',
'txt' => 'text');
foreach($array as $key => $value)
{
$template = str_replace('{'.$key.'}', $value, $template);
}
echo $template;
Now instead of echo the template I just want to add include "file.html" and it will display the file with correct variable values and I want to put the engine in a separate place and just include it in the template what I want to use it declare the array and at the end include the html file like phpbb. Sorry I am asking to much but can anyone just explain the basic concept behind this?
EDIT: Well let me be frank i am making a forum script and i have got tons of ideas for it but i want make its template system like phpbb so i need a separate template engine custom one if you can help then please you are invited to work with me. sorry for the ad.. :p
file.html:
<html>
<body>
<h3>Hi there, <?php echo $name ?></h3>
</body>
</html>
file.php:
<?php
$name = "Keshav";
include('file.html');
?>
Doesn't get simpler than this. Yes, it uses global variables, but if simple is the name of the game, this is it. Simply visit 'http://example.com/file.php' and off you go.
Now, if you want the user to see 'file.html' in the browser's address bar, you'd have to configure your webserver to treat .html files as PHP scripts, which is a little more complicated, but definitely doable. Once that's done, you can combine both files into a single one:
file.html:
<?php
$name = "Keshav";
?>
<html>
<body>
<h3>Hi there, <?php echo $name ?></h3>
</body>
</html>
What if, for a script easier to maintain, you move those to functions?
something like this:
<?php
function get_content($file, $data)
{
$template = file_get_contents($file);
foreach($data as $key => $value)
{
$template = str_replace('{'.$key.'}', $value, $template);
}
return $template;
}
And you can use it this way:
<?php
$file = '/path/to/your/file.php';
$data = = array('var1' => 'value',
'txt' => 'text');
echo get_content($file, $data);
Once you iron out all bugs, fix huge performance problem you're getting yourself into, you'll end up with template engine just like Smarty and otheres.
Such find'n'replace approach is much slower than compilation to PHP. It does not handle escaping very well (you'll run into XSS problems). It will be quite difficult to add conditions and loops, and you will need them sooner or later.
<?php
class view {
private $file;
private $vars = array();
public function __construct($file) {
$this->file = $file;
}
public function __set($key, $val) {
$this->vars[$key] = $val;
}
public function __get($key, $val) {
return (isset($this->vars[$key])) ? $this->vars[$key] : null;
}
public function render() {
//start output buffering (so we can return the content)
ob_start();
//bring all variables into "local" variables using "variable variable names"
foreach($this->vars as $k => $v) {
$$k = $v;
}
//include view
include($this->file);
$str = ob_get_contents();//get teh entire view.
ob_end_clean();//stop output buffering
return $str;
}
}
Here's how to use it:
<?php
$view = new view('userprofile.php');
$view->name = 'Afflicto';
$view->bio = "I'm a geek.";
echo $view->render();

Categories