In PHP we can pass arguments to a function dynamically during runtime. For example have look at this example.
I have used call_user_func_array() to pass the arguments to the function. The syntax would be:
[code language=”php”]
call_user_func_array(function, param_arr)
[/code]
Since I have used $_GET we can pass the function and its arguments during runtime.
http://localhost/?func=user&args[]=Osanda&args[]=secret&args[]=abc@abc.com
When we pass the URL like that the actual parameters would be like the following.
[code language=”php”]
call_user_func_array("user", [‘Osanda’, ‘secret’, ‘abc@abc.com’]);
[/code]
Don’t you see the loophole? 😉 Why not we can call any PHP function. The first thing that comes to my mind is phpinfo()
http://localhost/?func=phpinfo&args[]=-3
What about code execution? Yeah it is possible. For example we can call passthru() and pass the arguments nicely.
http://localhost/?func=passthru&args[]=systeminfo | findstr /C:"OS"
The simplest way to mitigate these kind of arbitrary calling of functions you could add a prefix to your functions. You can of course think of better solutions than this depending on your situation. But in this case for example instead of:
[code language=”php”]
function User($user, $pass, $email)
[/code]
you can add something like
[code language=”php”]
function secure_User($user, $pass, $email)
[/code]
Also make sure you concatenate the prefix to the GET request in call_user_func_array()
[code language=”php”]
call_user_func_array("secure_".$_GET[‘func’], $_GET[‘args’]);
[/code]
Now if you try to request any arbitrary function PHP will throw an error since we have concatenated “secure_” prefix to the calling function.
http://localhost/?func=system&args[]=dir
Thanks for reading!
Fantastic article. And it leads to the saying: “always sanitize your inputs”.
Thank you Sir!
I hope nobody ever will think to use something like this in production.
Let’s hope 🙂 but you can find plenty of places where dynamic function calling is done 🙂
Really nice article this is improving programming skill and increasing my knowledge about it. I know about the dynamic function in the PHP Development course and some doubts are clear through this article, this is more useful for me.