Tuesday, October 27, 2015

How to prevent SQL-Injection in PHP?


Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
  1. Using PDO (for any supported database driver):
    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    
    $stmt->execute(array('name' => $name));
    
    foreach ($stmt as $row) {
        // do something with $row
    }
  2. Using MySQLi (for MySQL):
    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);
    
    $stmt->execute();
    
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row
    }
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (e.g. pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are thrown as PDOExceptions.
What is mandatory however is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employeesthe result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array('column' => $unsafeValue));

Can Prepared Statements Be Used For Dynamic Queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
// Value whitelist
  // $dir can only be 'DESC' or 'ASC'
$dir = !empty($direction) ? 'DESC' : 'ASC'; 

Wednesday, October 14, 2015

Example of Client-Server Program in C (Using Sockets and TCP)

Below you’ll find an example of a very simple client-server program in C. Basically the client connects to the server, the server sends the message “Hello World”, and the client prints the received message.
Keep in mind that I am configuring the settings manually. If you want your code to be IPV4-IPV6 agnostic, IP agnostic and portable to different plataforms you can use the getaddrinfo() function, as explained in this tutorial.
Second, I am not doing error checking on most function calls. You should implement those checks if you are going to use the code for a real project.
Third, if you want more details about the functions or their arguments please check the man page of each one.
Finally, to test the code you just need to run the server on a terminal and then run the client on a different terminal (or run the server as a background process and then run the client on the same terminal).
Server Code
/****************** SERVER CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){   int welcomeSocket, newSocket;   char buffer[1024];   struct sockaddr_in serverAddr;   struct sockaddr_storage serverStorage;   socklen_t addr_size;   /*---- Create the socket. The three arguments are: ----*/   /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */   welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);      /*---- Configure settings of the server address struct ----*/   /* Address family = Internet */   serverAddr.sin_family = AF_INET;   /* Set port number, using htons function to use proper byte order */   serverAddr.sin_port = htons(7891);   /* Set IP address to localhost */   serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");   /* Set all bits of the padding field to 0 */   memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);     /*---- Bind the address struct to the socket ----*/   bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));   /*---- Listen on the socket, with 5 max connection requests queued ----*/   if(listen(welcomeSocket,5)==0)     printf("Listening\n");   else     printf("Error\n");   /*---- Accept call creates a new socket for the incoming connection ----*/   addr_size = sizeof serverStorage;   newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);   /*---- Send message to the socket of the incoming connection ----*/   strcpy(buffer,"Hello World\n");   send(newSocket,buffer,13,0);   return 0; }
Client Code

/****************** CLIENT CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){   int clientSocket;   char buffer[1024];   struct sockaddr_in serverAddr;   socklen_t addr_size;   /*---- Create the socket. The three arguments are: ----*/   /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */   clientSocket = socket(PF_INET, SOCK_STREAM, 0);      /*---- Configure settings of the server address struct ----*/   /* Address family = Internet */   serverAddr.sin_family = AF_INET;   /* Set port number, using htons function to use proper byte order */   serverAddr.sin_port = htons(7891);   /* Set IP address to localhost */   serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");   /* Set all bits of the padding field to 0 */   memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);     /*---- Connect the socket to the server using the address struct ----*/   addr_size = sizeof serverAddr;   connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);   /*---- Read the message from the server into the buffer ----*/   recv(clientSocket, buffer, 1024, 0);   /*---- Print the received message ----*/   printf("Data received: %s",buffer);     return 0; }

Wednesday, October 7, 2015

Creating a RESTful API with PHP

Creating a RESTful API with PHP

What is REST?
REST, or in the full form, Representational State Transfer has become the standard design architecture for developing web APIs. At its heart REST is a stateless client-server relationship; this means that unlike many other approaches there is no client context being stored server side. To counteract that, each request contains all the information necessary for the server to authenticate the user, and any session state data that must be sent as well.

REST takes advantage of the HTTP request methods to layer itself into the existing HTTP architecture. These operations consist of the following:
  • GET - Used for basic read requests to the server
  • PUT- Used to modify an existing object on the server
  • POST- Used to create a new object on the server
  • DELETE - Used to remove an object on the server
By creating URI endpoints that utilize these operations, a RESTful API is quickly assembled.

What is an API

In this sense an API - which stands for Application Programming Interface - allows for publicly exposed methods of an application to be accessed and manipulated outside of the program itself. A common usage of an API is when you wish to obtain data from a application (such as a cake recipe) without having to actually visit the application itself (checking GreatRecipies.com). To allow this action to take place, the application has published an API that specifically allows for foreign applications to make calls to its data and return said data to the user from inside of the external application. On the web, this is often done through the use of RESTful URIs. In our cake example the API could contain the URI of

greatrecipies.com/api/v1/recipe/cake

The above is a RESTful endpoint. If you were to send a GET request to that URI the response might be a listing of the most recent cake recipes that the application has, a PUT request could add a new recipe to the database. If instead you were to request /cake/141 you would probably receive a detailed recipe for a unique cake. These are both examples of sensible endpoints that create a predictable way of interacting with the application.


Making Our Own RESTful API

The API that we're going to construct here will consist of two classes. One Abstract class that will handle the parsing of the URI and returning the response, and one concrete class that will consist of just the endpoints for our API. By separating things like this, we get a reusable Abstract class that can become the basis of any other RESTful API and have isolated all the unique code for the application itself into a single location.

However, before we can write either of those classes there's a third part of this that must be taken care of.

Writing a .htaccess File

A .htaccess file provides directory level configuration on how a web server will handle requests to resources in the directory the .htaccess file itself lives in. Since we do not wish to have to create new PHP files for every endpoint that our API will contain (for several reasons one of which being that it creates issues with maintainability); instead we wish to have all requests that come to our API be routed to the controller which will then determine where the request intended to go, and forward it on to the code to handle that specific endpoint. With that in mind, let's create a .htacccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule api/v1/(.*)$ api/v1/api.php?request=$1 [QSA,NC,L]
</IfModule>

What Did That Do?

Let's walk through this file. The first thing that we do here is wrap everything in a check for the existence of mod_rewrite.c; if that Apache module is present, we can continue. We then turn the RewriteEngine On and prepare it to work by giving it two rules. These rules say to perform a Rewrite if the requested URI does not match an existing file or directory name.

In the next line declares the actual RewriteRule. This says that any requests to api/v1/ that is not an existing file or directory should instead be sent to api/v1/index.php. The (.*) marks a named capture, which is sent along to the MyAPI.php script as well in the request variable through the use of the $1 delimiter. At the end of that line are some flags that configure how the rewrite is performed. Firstly, [QSA] means that the named capture will be appended to the newly created URI. Second [NC] means that our URIs are not case sensitive. Finally, the [L] flag indicates that mod_rewrite should not process any additional rules if this rule matches.

Constructing the Abstract Class

With our .htaccess file in place, it is now time to create our Abstract Class. As mentioned earlier, this class will act as a wrapper for all of the custom endpoints that our API will be using. To that extent, it must be able to take in our request, grab the endpoint from the URI string, detect the HTTP method (GET, POST, PUT, DELETE) and assemble any additional data provided in the header or in the URI. Once that's done, the abstract class will pass the request information on to a method in the concrete class to actually perform the work. We then return to the abstract class which will handle forming a HTTP response back to the client.

Firstly we're going to declare our class, its properties, and constructor:
abstract class API
{
    /**
     * Property: method
     * The HTTP method this request was made in, either GET, POST, PUT or DELETE
     */
    protected $method = '';
    /**
     * Property: endpoint
     * The Model requested in the URI. eg: /files
     */
    protected $endpoint = '';
    /**
     * Property: verb
     * An optional additional descriptor about the endpoint, used for things that can
     * not be handled by the basic methods. eg: /files/process
     */
    protected $verb = '';
    /**
     * Property: args
     * Any additional URI components after the endpoint and verb have been removed, in our
     * case, an integer ID for the resource. eg: /<endpoint>/<verb>/<arg0>/<arg1>
     * or /<endpoint>/<arg0>
     */
    protected $args = Array();
    /**
     * Property: file
     * Stores the input of the PUT request
     */
     protected $file = Null;

    /**
     * Constructor: __construct
     * Allow for CORS, assemble and pre-process the data
     */
    public function __construct($request) {
        header("Access-Control-Allow-Orgin: *");
        header("Access-Control-Allow-Methods: *");
        header("Content-Type: application/json");

        $this->args = explode('/', rtrim($request, '/'));
        $this->endpoint = array_shift($this->args);
        if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) {
            $this->verb = array_shift($this->args);
        }

        $this->method = $_SERVER['REQUEST_METHOD'];
        if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
            if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
                $this->method = 'DELETE';
            } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
                $this->method = 'PUT';
            } else {
                throw new Exception("Unexpected Header");
            }
        }

        switch($this->method) {
        case 'DELETE':
        case 'POST':
            $this->request = $this->_cleanInputs($_POST);
            break;
        case 'GET':
            $this->request = $this->_cleanInputs($_GET);
            break;
        case 'PUT':
            $this->request = $this->_cleanInputs($_GET);
            $this->file = file_get_contents("php://input");
            break;
        default:
            $this->_response('Invalid Method', 405);
            break;
        }
    }
}

By declaring this an abstract class we're prohibited by PHP from creating a concrete instance of this class. From there we can create some protected class members. A protected member can only be accessed in the class itself and children thereof, unlike a private variable which can only be accessed in the class that defined the member.

Let's Talk About CORS

One of the core premises of an API is that clients on different domains than the one the API is hosted on will be connecting to the API to send and receive data. There is an inherit security risk here, as this can allow an attacker to create an imitation page and steal data sent back and forth. Therefore this ability must be explicitly enabled on pages that wish to allow what is called Cross-Origin Resource Sharing, aka CORS. One excellent resource to learn more about CORS is the website Enable CORS - it was quite helpful to me as I was trying to understand things.

For our API we need to make sure that this is enabled, so the very first thing that is done in the __construct method is to set some custom headers. The first two are the magic; firstly we allow requests from any origin to be processed by this page, next we allow for any HTTP method to be accepted.

Once the surprisingly simple yet completely crucial step of allowing CORS requests has been completed, it becomes time for our script to understand what the client has asked of it. To do that we're going to take the $request variable which will be sent to our script from the .htaccess file (remember? it contains the original URI that the client requested), and tear it apart into the components we need. Once it's been exploded around the slash by pulling off the very first element we can grab the endpoint, if applicable the next slot in the array is the verb, and any remaining items are used as $args.

The HTTP method will describe the purpose of this request. GET requests are easy to detect, but DELETE and PUT requests are hidden inside a POST request through the use of the HTTP_X_HTTP_METHOD header. Once a method has been picked, the appropriate data source is parsed and cleaned for safety before being executed.

Completing the Abstract Class

The rest of the Abstract class comes next. Right now we're missing a function that will call the methods in the concrete class, and then one that will handle returning the response. Here's the rest of the abstract class:
abstract class API
{
    ...

    public function processAPI() {
        if (method_exists($this, $this->endpoint)) {
            return $this->_response($this->{$this->endpoint}($this->args));
        }
        return $this->_response("No Endpoint: $this->endpoint", 404);
    }

    private function _response($data, $status = 200) {
        header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
        return json_encode($data);
    }

    private function _cleanInputs($data) {
        $clean_input = Array();
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $clean_input[$k] = $this->_cleanInputs($v);
            }
        } else {
            $clean_input = trim(strip_tags($data));
        }
        return $clean_input;
    }

    private function _requestStatus($code) {
        $status = array(  
            200 => 'OK',
            404 => 'Not Found',   
            405 => 'Method Not Allowed',
            500 => 'Internal Server Error',
        ); 
        return ($status[$code])?$status[$code]:$status[500]; 
    }
The one function worth mentioning here is the processAPI() method. This is the one publicly exposed method in the API, and its job is to determine if the concrete class implements a method for the endpoint that the client requested. If it does, then it calls that method, otherwise a 404 response is returned. The rest of the new code is simply an array map of all the possible HTTP codes and an input sanitizer.

That's all there is for the Abstract class. Now, finally time to implement a Concrete example.

Creating a Concrete API

Think back to our talk earlier about Cross-Origin Resource Sharing (CORS). Remember how it introduces a security vulnerability? We're going to work to close that as tightly as possible here by tying an Origin to a unique API Key. This means that only known and allowed external hosts will be able to connect to our API service through a pairing of their domain name and a uniquely generated API Key. For the purposes of this example I'm going to leave some of the code to verify the API Key abstracted out. Additionally our API will require a unique token in every request to verify the User.
require_once 'API.class.php';
class MyAPI extends API
{
    protected $User;

    public function __construct($request, $origin) {
        parent::__construct($request);

        // Abstracted out for example
        $APIKey = new Models\APIKey();
        $User = new Models\User();

        if (!array_key_exists('apiKey', $this->request)) {
            throw new Exception('No API Key provided');
        } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) {
            throw new Exception('Invalid API Key');
        } else if (array_key_exists('token', $this->request) &&
             !$User->get('token', $this->request['token'])) {

            throw new Exception('Invalid User Token');
        }

        $this->User = $User;
    }

    /**
     * Example of an Endpoint
     */
     protected function example() {
        if ($this->method == 'GET') {
            return "Your name is " . $this->User->name;
        } else {
            return "Only accepts GET requests";
        }
     }
 }

Using the API

Creating the concrete class is as simple as that. For each additional endpoint you wish to have in your API, simply add new functions into the MyAPI class whose name match the endpoint. You can then use the $method and $verb and $args to create flow paths within those endpoints.

To actually implement the API we need to create the PHP file that the .htaccess file is forwarding all of the requests to. In this example I named it api.php:

// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}

try {
    $API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
    echo $API->processAPI();
} catch (Exception $e) {
    echo json_encode(Array('error' => $e->getMessage()));
}

If you visit /api/v1/example (and have the User and Token system setup) you should see the output from that endpoint there.

That's a Wrap

That's all there is to it...which is, well, really quite a lot actually.

Thursday, October 1, 2015

Native vs Hybrid Mobile App Development


People enjoy using their smartphones because they can accomplish many things on the go such as reading e-mails, social networking, watching movies and plenty of other activities. We enjoy smartphones because they have many applications that make everyday activities easier.

If you are thinking of developing for the mobile application market, an important decision is to decide between developing a native application or a hybrid one.

It’s an age old question that refuses to go away, we thought it was time to revisit… Which is the best?

Native over Hybrid

Building native applications means using the native language of the platform, Objective-C on iOS, and Java on Android. The main advantage of native applications is their performance. Native apps are compiled into machine code (Dalvik byte code under Android), which gives the best performance you can get from the mobile phone.

Best performance includes fast and fluid animations as well as full access to phone hardware, multi touch support and the latest APIs.

Native development is far from easy. Despite the great number of resources that can be found, it may not be understandable to everyone. As code must be written specifically for each platform, the same code will have to largely be rewritten with little able to be shared. The logic may be the same, but the language, APIs and the development process is different. This process can be relatively long for complex applications.

Going Native

If you are new to mobile development and want to build performance-critical mobile apps and/or take advantage of native APIs, you would need a good resource on learning mobile native development.

Let’s take iOS for example. If you want to be a native iOS developer, firstly get yourself a Mac. You can write code anywhere, but a Mac is needed to build the code into an application as is an iOS Developer Account ($99 per year).

You can get a great intro to Objective-C by creating your own Flappy Bird game in your browser. A single online tutorial won’t quite do the trick though, Apple provides its own tutorial which is helpful for beginners and experienced developers. This tutorial introduces application design, structure and code implementation while building a ToDoList app (ToDo lists seem to be the ‘Hello, World!’ applications for mobile development).

As for Android development, I would recommend Learning Android, 2nd Edition by O’Reilly. It gives a good insight at of Android development while building a Twitter-like mobile client.

Hybrid over Native

Hybrid applications are web applications (or web pages) in the native browser, such as UIWebView in iOS and WebView in Android (not Safari or Chrome). Hybrid apps are developed using HTML, CSS and Javascript, and then wrapped in a native application using platforms like Cordova. This allows you to use any web-native framework you want, and there are plenty of these.

The application development is faster, simpler, more rapid and the application is easier to maintain. You can change platforms anytime you need, Cordova lets you build your application for more than one platform just by one adding line of code. As for the phone hardware such as the camera or Bluetooth, Cordova has a large repository of plugins you may use.

The main problem with hybrid apps is that they still depend on the native browser, which means they are not as fast as native apps.

Going Hybrid

If you decided to develop hybrid applications, then you should know that there are two main ‘competitors’ in this field. One is Cordova (and Cordova-based tools like PhoneGap) and the other is Appcelerator Titanium. They both target mobile platforms but work in very different ways.

Developing with Cordova is just like developing a webpage. You create HTML, CSS and JavaScript local files, test them in the browser and then wrap them in a native web view with Cordova (you’ll still need native SDKs and development tools for this step).

Using Titanium is a bit different, you don’t any HTML and CSS files, unless you want to create an application that uses both native and HTML-based User Interfaces. Titanium provides a very useful mobile tool set that helps you emulate (or simulate) your application on the real platform, not in the browser. When your app is run on the device, it doesn’t get wrapped into a web view, but gets interpreted by a Javascript engine (JavaScriptCore in iOS or Rhino in Android).

Appcelerator provides a good tutorial (surprisingly not a ToDo application).

There are also several other less known hybrid development options such as Xamarin, Rho, Corona and MoSync. All of these work in slightly different ways and may benefit you more depending on your current programming experience.

Conclusion

Both native and hybrid are ways to fulfill the different needs and preferences of users and developers, and none of them can be thought as a perfect solution. They have their strengths and weaknesses and it is up to you to decide which of them fits you better and which one you will use in your application.