Is exposing class and method names in the URL unsecure? - php

I don't use any famous framework and I've created my own one. It is actually kind of a advanced MVC. Anyway, Its routing is totally different than other frameworks. I mean, there isn't any file named route containing all routes. It will call the needed class and function automatically based on the URL. For example:
http://example.com/classname/methodname/arg1/arg2
URL above calls this script by using autoloader:
class classname{
public function methodname() {
// do stuff
}
}
See? Everyone will know the name of class or method in my script. My question is, is that secure enough? Or is there something particular that I should know?

It depends. If your framework allows arbitrary classes and function to be invoked, this means you effectively build a remote shell with a web interface. In other words: maximum insecure.
Likewise, if your application also allows file uploads, a malicious user might be able to upload their own PHP classes and then invoke it from your URLs. Without further details about your framework, it's hard to say. But you probably want to whitelist what can be called this way.
Even if the framework has some protection measures to control what code can be called, I am not a friend of leaking implementation details like this to the public. You tied your public API to a specific implementation with this. That will make it harder to change the code while maintaining the same API for clients to call.

Related

Private methods in Controller in MVC project

is it OK if I have private methods in the controller in a MVC project? I mean, is it a good practice?
Here is what I mean:
I have a method settings in my User controller which is for changing emails and passwords.
public function settings($settings)
{
/**
* Check if the user is logged in
*/
$auth = new Authenticate($this->user_type);
if(!$auth->isUser())
{
redirect(SITE_ADDR.'/public/home');
}
switch ($settings)
{
default:
error_404();
break;
case "email":
self::change_email();
break;
case "password":
self::change_password();
break;
}
}
And as you can see the switch in this method is calling other methods from the same class which are private. The reason for this is because I don't want someone to manually modify the URL and access the methods and then get all kinds of errors like this: http://localhost/MVC/public/user/change_email
The correct urls have the following structure: http://localhost/MVC/public/user/settings/email.
Currently there are 2 private methods - for changing email and password but I plan on having more - adding profile details (like real name, description, etc.), possibly connecting facebook or other social media accounts, etc. I don't want my settings method to be too long.
So what do you think, is this a good idea?
It is perfectly fine in any OO context to have private methods. Visibility modifiers like protected and private serve to keep your code modular and encapsulated. They prevent that other code is written against it, that some other code outside the class would call those methods. The point of that is that you have more control over what calls what and that you have more confidence to refactor code later on without being unsure about whether you need to keep a certain method around in order to not break other code. A private method can only be called from within the same class, which greatly reduces the amount of code you need to check if you ever rewrite that method.
How that relates to publicly callable URLs is an entirely separate issue. I'd argue that visibility modifiers shouldn't be your primary method of distinguishing between a method exposed as HTTP endpoint and an internal implementation detail. Visibility modifiers are for control over your code coupling, HTTP endpoints should be defined by configuration separately from that. That many frameworks use visibility modifiers as convenience "security" feature for implicitly mapped HTTP endpoints isn't necessarily a good pattern.
Write good OO code in whatever way necessary; if it makes sense to separate some code into a method which doesn't need to be public, then by all means go for a private method.
Configure how URLs map to class methods in some sensible manner.
Don't necessarily conflate those two completely separate things.
Yes, this is an ok practice to follow, as long as the project calls for it
In most cases it is probably a bad practice, as controllers should use services to share logic, and receive those services using dependency injection, which isn't inherent to the MVC pattern, but most recent MVC frameworks use it.
When your controller is only making calls to services and not doing lots of low level logic itself then there really isn't a lot to gain from creating shortcut private methods on your controller to those services or their actions.
Though it does seem preferable to just duplicating all the code everywhere, especially if there are lots of lines of code.
But if you're having that much logic in your controllers it is probably a sign that you should be moving some things to service classes.

Which is more secure? A function in a helper or in a controller

I am creating an application with the help of codeigniter. People can register and log in to the application. User can view each others profile as well.
I noticed that I am using the functions like getting a username from user id, email from user id...... quite a lot. The common thing I noticed about all these functions is that they all are supplied with a user id as its parameter. All these functions are in the controller.
I was thinking to put all these functions in a helper file. As it is quite easy to call the function from helper file. Since, I am using these functions quite a lot, I can directly use them in views if they are from helper file.
Now my question is, is it safe to put these functions in helper instead of controller from the security point of view ? As these functions directly access the database to get the crucial information from the users table.
I know this question might be regarded as very much to a opinion based. But at the same time, I am trying to get the exact answer whether it is safe or not.
From a "secure" standpoint, they're both in your code and not visible by the end user. From a testing standpoint though, code that accesses your database is best tested when it's isolated from code touching other components like UI (which is generally in the controller). This sort of thing would normally go into the model or model helpers in an MVC pattern.

PHP MVC: Do i really need a Controller?

My question is simple but (I guess) hard to answer:
Do I really need a complete Model-View-Controller design pattern in my PHP Website / Web-App?
I can't understand how a Controller could be useful with PHP since every PHP site is generated dynamically on every request. So after a site is generated by PHP, there is no way to let the View (the generated HTML site in the Browser) interact with the controller, since the Controller is on the server side and generated once for each site request, even if the request is AJAX...
Do I understand something completely wrong?
Why should I use any kind of MVC PHP Framework like Zend or Symphony?
EDIT:
For example lets assume, there should be a website to represent a list of customers in a table:
My Model would be a simple Class Customer on the server side that queries the database.
My View would be the generated HTML code that displays the Model (list of Customers).
And the controller? Is the controller only evaluating the GET or POST to call the correct method of the model?
Do I have understand something completely wrong?
Yes.
The MVC pattern is not for the browser. The browser sees HTML anyways. Whether this HTML is generated with C++, PHP, Java or whatever it doesn't matter. The browser doesn't care what design patterns were used to generate this HTML.
MVC is a design pattern to organize and separate responsibilities in your code. So it's not for the browser, it's for the developers writing the code. It's to create more maintainable code where you have a clear separation between your business logic (Model), the communication between the model and the view (Controller) and the UI (View).
Whether you should use the MVC pattern in your web site is a subjective question that I prefer not to answer as it will depend on many factors.
Short Answer
Yes. A controller will be responsible for preparing data to display for rendering and sometimes handle GET and POST requests that originating from your client. It should leave HTML generation to the view.
Long Answer
MVC can be very helpful in keeping applications maintainable and your code base sane. The pattern helps ensure separation of concerns of your code and in most cases will steer yor clear of 'spaghetti php' where your application logic is tangled with the HTML generation. A sample MVC setup below (there are sure to be many variations of this, but it gives you the idea):
Model
Responsible for fetching data from the database and saving changes when requested. One example might be a php object that represents a user with name and email fields.
Controller
Responsible for massaging and manipulating data and preparing it for display. The prepared data is passed to a view for rendering, with the view only needing to be aware of just the data it needs to render. For example: a controller may look at a query string to determine what item to fetch to render and combine this with several additional model queries to get additional data.
Often controllers will also be responsible for handling GET and POST requests that originate from your HTML client and applying some sort of manipulation back on your database. For example - handling form submits or AJAX requests for additional data.
View
The view is responsible for actually generating the HTML for display. In PHP, a view would often be a template file with minimal logic. For example, it might know how to loop over items provided to it from the controller or have some basic conditionals.
Application MVC vs PHP/Python/etc. MVC
From your other comments it sounds like you are familiar with using MVC in the context of a desktop or mobile application.
One of the main differences between MVC in the two is the granularity at which the controller is manipulating the view and responding to events.
For example, in a traditional application the controller might listen for click events originating from a button and respond appropriately.
When your doing server side html generation however, your controller is only 'alive' for a brief moment while its preparing html to ship out over the wire. This means that it can only do so much to setup and prepare the view for display.
Instead of listening traditional events from the UI, it can instead react in different ways to future GET and POST requests. For example, you may have a "save" button on a form trigger a POST request to your server (such as yourpage.php?action=save&value=blah). While handling this request your controller might access your models and apply changes, etc.
I realise that I am answering a very old questions, however, I do not believe that any other question has answered your initial concern appropriately, and this will hopefully add something useful for others who may stumble across this question in their learning about MVC.
Firstly, I will start by saying I read an interesting article about the confusion which exists within the PHP community about MVC and it is worth a read if you are asking this type of question.
Model-View-Confusion part 1: The View gets its own data from the Model
Secondly, I do not believe you have misunderstood anything at all, rather you have a better understanding of PHP and MVC which is allowing you to ask the question. Just because something has been defined and accepted by the community at large, it does not mean you should't question its use from time to time. And here is why.
There is NO memory between requests (except for SESSION state) within a PHP application. Every time a request is received the entire application fires up, processes the request and then shuts down i.e. there are no background application threads left running in the background (at least none which you can use within your application) where you could, theoretically, maintain application state. This is neither good, nor bad, it is just the way it is.
Understanding this, you can probably start to see what you are thinking is correct. Why would a View (which is allowed to access its own data from the Model) need a Controller? The simple answer, is that it doesn't. So for the pure display of a Model, the View is perfectly entitled to fetch its own data (via the Model) and it is actually the correct way to implement MVC.
But wait. Does this mean we don't need Controllers? Absolutely NOT! What we need to do is use a Controller for its appropriate purpose. In MVC, the Controller is responsible for interpreting user requests and asking the Model to change itself to meet the users request, following this, the Model can notify it's dependencies of the change and the View can update itself. Obviously, as you know, in the context of a PHP web application, the View is not just sitting and waiting for update notifications. So how can you achieve the notification?
This is where I believe MVC got hijacked. To notify the View it's Model has changed, we can simply direct them to the URL of the View which accesses the now updated Model. Great, but now we have introduced something into the Controller. Something which says, "Hey, I'm a controller but now I have knowledge of the location of the View." I think at this point, someone thought, "why do I bother redirecting the user? I have all the data which the View needs why don't I just send the data directly to the View?" and bang! Here we are.
So let's recap.
A View CAN access the Model directly within MVC
The Model houses the business logic for the Domain Objects
A Controller is not meant to provide the View access to the Model or act as any type of mediator
The Controller accepts user requests and makes changes to it's Model
A View is not the UI/HTML, that is where a Template is used
A practical example
To explain what I have been describing, we shall look at a simple, commonly found function within most websites today. Viewing the information of a single logged in user. We will leave many things out of our code here in order to demonstrate just the structure of the MVC approach.
Firstly lets assume we have a system where when we make a GET request for /user/51 it is mapped to our UserView with the appropriate dependencies being injected.
Lets define our classes.
// UserModel.php
class UserModel {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
public function findById($id) {
return $this->db->findById("user", $id);
}
}
// UserView.php
class UserView {
private $model;
private $template;
private $userId;
public function __construct(UserModel $model, Template $template) {
$this->model = $model;
$this->template = $template;
}
public function setUserId($userId) {
$this->userId = $userId;
}
public function render() {
$this->template->provide("user", $this->model->findById($this->userId));
return $this->template->render();
}
}
And that's it! You do not require the Controller at all. If however you need to make changes to the Model, you would do so via a Controller. This is MVC.
Disclaimer
I do not advocate that this approach is correct and any approach taken by any developer at any point in time is wrong. I strongly believe that the architecture of any system should reflect its needs and not any one particular style or approach where necessary. All I am trying to explain is that within MVC, a View is actually allowed to directly access it's own data, and the purpose of a Controller is not to mediate between View and Model, rather it is intended to accept user requests which require manipulation of a particular Model and to request the Model to perform such operations.

PHP OOP - How to handle authorisation?

I'm building a management system for an idea I have. I'm well versed in PHP (at least enough to do everything I need to do) but I'm not that experienced with using OOP. I use it as much as I can but a lot of the best practices I'm not familiar with so when I do things I worry I'm doing them in the wrong order.
For this project I have a class for the thing the user is managing, I need to check whether or not the user has permissions to manage it. I know how to check the permissions, my question is: where should I be doing it?
Should I be doing it outside the class, like so:
if user permissions are valid
initialize class
else return error
or should I be doing
initialize class
class checks permissions
class returns error if permissions are invalid
I'm unsure which is the correct approach. On the one hand checking within the class seems the best based on what I know of OOP methodology, but then I also have the feeling that letting it get as far as initializing the class when permissions are unknown might be bad.
How should I be doing it? If there's any sort of article that covers this sort of thing a link would be greatly appreciated (I can't find anything through searches but I'm not 100% sure if I'm searching for the right thing as I know little of OOP)
It depends on what is your permissions model, and there is no "one correct way" to do it. It's a matter of approach. The important thing, is that whatever you choose, you use it consistently.
In my latest projects, I came across several different models. One of the most straightforward is a page-based permission, which is good if you do page-based flow, and use objects for support: you define at the top of the page who is supposed to access it and in case you can redirect. This is the simplest one, but can be very useful on specific applications.
If you, on the contrary, use objects to do your main flow, you should secure your object methods (rather than class instantiation). If you have a "save()" method, which can be called by specific users only, first thing when you enter that method, do your permissions check.
I am currently using an MVC pattern, and I have a Controller, which dispatches the actions to its children. Its only public method is execAction($params) and it will call actionAction($params) on itself, but first it will check permissions.
One important thing to remember is: never present actions on the UI that the user is not allowed to do (unless you are trying to force him to buy your "PRO version", that is) ;-)
I have written a pretty solid and robust CMS system. Here's how I do it and I hope you can extrapolate some information on making your own solution.
I have an index file, which loads an Admin class. Functionality in my CMS is modular (so containing in its own file and class).
A module is loaded based on a $_GET parameter.
Because the function to check the $_GET parameter and load the corresponding function is in my Admin class ($admin->pick_method()) and I also have a User object in my Admin class, I can first check the requested module is in the currently logged in user's permissions array.
If the permissions check returns true, I load the module. If false, I display a friendly "unauthorized access" page.
Hope this helps.
I think best way to do is to have class of permissions.
And then you can check before creating object or in object.
create permission class
if access then create class and set permission object
else error
// do action
if have permissions show something
else do not show something
Look how done in zend acl component
Validating within the class generates a dependency between the class and the permissions authorisation which isn't good because you are tying together two potential disparate items. You can solve this by Inversion of Control (eg. dependency injection) or as I do by authorisation notifications using Emesary.
Validating outside of the class is possibly worse because there is a real danger that the authorisation check will be wrong or missed completely. It also creates the wrong sort of linking between objects as the object is not in control of itself.
If you are going to do it outside of the object when it is created then it is probably better to require the object to provide an interface such as IAuthorisable which can be verified by a seperate object.
e.g.
interface IAuthorisable
{
public function getRequirements();
}
class Authorisation
{
public static createObject($newObj)
{
if ( canDo( $newObj->getRequirements()) )
return $newObj;
return null;
}
}
class Something implements IAuthorisable
{
public function getRequirements()
{
return SomeSortOfIdentifierOrSomething;
}
}
$mySomething = Authorisation::createObject(new Something($p1, $p2), "
If $mySomething is null it isn't allowed. Obviously this needs extending and designing properly which is left as an exercise for the reader.
OO basics
If it makes sense to include it in the class. You could do it.
Does a Book class have an authenticate function? No, functions like download() and convertToPDF() make more sense.
My approach
I always try to find the route of the least resistance.
If there are 10 scripts/pages that talk to 1 class and 1 or 2 scripts needs authentication for certain actions i would build the authentication into those 1 or 2 scripts. (or put them in a subfolder with a .htpasswd)
But when you're using a MVC structure, everything is a class, so its become a question of deciding which class.
I tend to put the authentication rules in the Controllers classes and the authentication to database-logic in a User class.

possible to make codeigniter work with another framework?

the situation is this.
my client (who also is a programmer) asks me to develop an address book (with mysql database) with a lot of functions. then he can interact with some class methods i provide for him. kinda like an API.
the situation is that the address book application is getting bigger and bigger, and i feel like its way better to use CodeIgniter to code it with MVC.
i wonder if i can use codeigniter, then in some way give him the access to controller methods.
eg. in a controller there are some functions u can call with the web browser.
public function create_contact($information) {..}
public function delete_contact($id) {..}
public function get_contact($id) {..}
however, these are just callable from web browser. how can i let my client have access to these functions like an API?
then in his own application he can use:
$result = $address_book->create_contact($information);
if($result) {
echo "Success";
}
$contact = $address_book->get_contact($id);
in this way, my controller methods are handling the in and out with the Models. there will be no views, cause i just have to return the data/result from the Models. and he can just use my "API" functions.
is this possible?
cause i just know how to access the controller methods with the webbrowser. and i guess its not an option for him to use header(location) to access them.
all suggestions to make this possible are welcomed! even other approaches to let me use CI to develop. perhaps there already are best practices regarding this kind of cross framework collaboration?
thanks
MVC seems to have dispersed in its definition. This definition I will offer should be ideal for you.
Models are where you build your business end of the application. Operations such as create_contact, delete_contact, and get_contact belong in the model layer. The model layer is what builds your application API and should be entirely independent.
Consider the controllers purely as the user's puppeteers. Controllers accept user input - the validation, sanitation, and whatnot may be done elsewhere - and invokes the API you've already setup in the model layer. Also, controllers then specify what view to use - however complicated or simple your presentation layer is.
The presentation layer usually isn't the difficulty. As long as you are only using read operations in the view you should be fine.
To clarify, if a user wants to create a new contact, the controller may need a method called create_contact that accepts the appropriate input. However, the actual operation of creating the contact must be done in the model layer. This will allow your other developer to reuse that same operation in a completely different application by loading your model, which was already designed as an independent entity.

Categories