Monday, May 8, 2017

Facebook Apps - OAuth 2.0


            Facebook apps are very popular due to various reasons. Most of the time these apps are built for entertainment purposes.
           When you see an attractive Facebook app you click on it. Once you clicked you can notice that they ask you to login as a Facebook, Twitter or Gmail user. That means by having one of these accounts you can use those apps without any problem. But these application owners, are they related to Facebook? or twitter? No! but then what is the connection between them? How we able to access someone else's application using Facebook account? Does Facebook know about this? You might have these questions in your mind.
          Actually these applications use OAuth protocol.
     OAuth (Open Authorization) is an open standard for token-based authentication and authorization on the Internet. OAuth, which is pronounced "oh-auth", allows an end user's account information to be used by third-party services, such as Facebook, without exposing the user's password.


In this blog post I am going to explain how to make a simple Facebook app like this using OAuth protocol.



But before that let's see what is happening behind this.

Study this diagram.



What is this token Facebook provides? actually Facebook provides two types of tokens. Access token and refresh token. Access token can be used several times before it gets expired. Once it is expired refresh token is sent to Facebook server in order to receive another access token along with a new refresh token.User can use this access token to get information from Facebook.

Let's start creating the app.

First we should go to facebook developer site and create an app there.

https://developers.facebook.com/



Go to "My Apps" on top right corner and select add new app.
This window will pop up. Enter required details and click "create App ID".


Now click on "Add Platform" on left corner navigation list. You will see something like this. Click on "Get started" in Audience Network.



You will see this area. In here you have to provide redirect URL in valid OAuth redirect URLs.
Facebook will send all his responses to this URL.  

In "settings" provide a App Domain and a Website URL. To provide a Website you have to click on "+ Platform" and then click on website.



In Dashboard you can see your app's App ID and App secret.




Now let's see how to use these values ( Redirection point URL, App ID, App secret ) to get resources from Facebook.

Obtain Authorization code from Facebook

For this we have to prepare the URL. This URL contains for elements.When we put these elements together all should be encoded using a URL encoding method. Parameter name, value and encoded value is given below.

1. response_type.     
    Code           
    Code                           

2. client_id
    1363180347108907
    1363180347108907

3. redirect_uri 
    http://localhost/team/
    http%3A%2F%2Flocalhost%2Fteam%2F

4. scope 
    public_profile user_posts user_friends user_photos
    public_profile%20user_posts%20user_friends%20user_photos

 Now combine these values and make the URL.




 Enter that URL in the URL bar of your browser and hit enter. Now you will see something like this. This is called as user consent page. In there you can see "Edit this" button. If you click on that you can manage the accessing resources.








Since you are the owner of this App you don't have to worry about privacy. Click on continue.

 This page will appear. 


 This page appear because for real you don't have a project which supports http://localhost/team/.
But check the URL. You can see authorization code is sent to you from Facebook. (highlighted)

http://localhost/team/?code=AQDRsjK348Gmy1upjm7vXVWPA5_n3A64gRs43npMFInR7b3H2-ibuf7s9vMaPnx3uqQt_oT2wx7XeICuIUlR2J-xICsHREiV5RmZ_-tqEPxKZYWfbI9qCtUopJBtLPkvC7KkPlWsshukf2siNYG1oAJTI87cYmNPC5_vhFdJeVAG7jqPu-Wbc1ACrLHMkCvMXXiWryWz0hMOGWMiZfgA8kteKuj0Y18fzL8vI156P1UiOiOr9pAz11OXrEPtga
7bZt4UJzzFJ0V8QJ0rof8Kc2HmKvGoaKpOC6oJBpR09fPo2fRs8umhQ5JMa4pHZwpm7j4nI-t4goKumDxpMMnlHG7R#_=_ 

Obtain access token

To obtain access token we have to have four parameters.
1. grant_type
    Authorization_code
2. client_id
    1363180347108907
3. redirect_uri
    http://localhost/team/
4. code
     AQDRsjK348Gmy1upjm7vXVWPA5_n3A64gRs43npMFInR7b3H2-ibuf7s9vMaPnx3uqQt_oT2wx7XeICuIUlR2J-xICsHREiV5RmZ_-tqEPxKZYWfbI9qCtUopJBtLPkvC7KkPlWsshukf2siNYG1oAJTI87cYmNPC5_vhFdJeVAG7jqPu-Wbc1ACrLHMkCvMXXiWryWz0hMOGWMiZfgA8kteKuj0Y18fzL8vI156P1UiOiOr9pAz11OXrEPtga
7bZt4UJzzFJ0V8QJ0rof8Kc2HmKvGoaKpOC6oJBpR09fPo2fRs8umhQ5JMa4pHZwpm7j4nI-t4goKumDxpMMnlHG7R#_=_



In the HTTP Headers, we need to add the Authorization header with the App credentials. 

App ID -  1363180347108907
App secret - c12fb940ca8e67d43d447f364861218b

AppID:App_secret
 1363180347108907:c12fb940ca8e67d43d447f364861218b

Now we have to encode this whole value using a base64 encoder.
 MTM2MzE4MDM0NzEwODkwNzpjMTJmYjk0MGNhOGU2N2Q0M2Q
0NDdmMzY0ODYxMjE4Yg==

To get the access token we have to specify the token endpoint. In this case it is this url
https://graph.facebook.com/oauth/access_token
 
Install RESTClient in your browser.

Give those values and obtain access token.



 

 Retrieve resources using access token

Method - GET
URL - https://graph.facebook.com/v2.8/me?fields=id
Authorization: Bearer <access token value>

 This will give user's ID in JSON object format.
 Using this ID you can get any information you want.

ex- you can uploaded posts.



Now let's see how to implement an app which can retrieve these information and output to the user.
I used php to develop this app.
Github link - https://github.com/sajith01prasad/Facebook-App---Oauth2.0.git

You have to have Facebook SDK v5 for PHP.  (You don't have to download this. I have added in it my project.  Check folder "facebook" in my project folder)
https://developers.facebook.com/docs/reference/php


index.php 





If you are not logged into Facebook only you will see the index page. Otherwise you will directly go to i.php which shows the results.

 This page is the main page where user directs to.


 Once the user clicks on "Click Here" button user will direct to i.php .


i.php




















 

 

Note:
The app I used for this has permissions for user friendlist. You can go to app review and check which permission you have.


Do not worry. If your app does not have that permission provide this instead of $permissions = ['email']; in both i.php and index.php files

$permissions = array("email","user_friends");
Otherwise you will not get killer's name.



 Look of this page is like this.


 You can see there is a button on the top of this page "Share on Facebook". Once the user clicks on this button automatically picture of index page with a caption of "Check out this app! It is awesome http://localhost/fb/i.php " will be uploaded on users timeline.

By calling facebook api I have received a few resources of user. name, profile picture, gender, timezone. According to the timezone I am assigning a country to the user. Since my application didn't go under Facebook review process I can't access many user information. (such as birthday, friend's profile picture etc).










 These are the files in the facebook php SDK v5




I hope you now you know how to make a Facebook app with the help of OAuth from the scratch.
Cheers. !!!











Monday, May 1, 2017

SQL injection with examples.



SQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution. Attacker can use this technique to manipulate the database as he wants.
The main reason for sql injection attacks is parsing user inputs as query parameters in the URL. That means using GET method in forms. When we use GET method we clearly can see what parameters are going through the URL with their values. This is very dangerous.
There are so many tools out there we can use in order to find out whether a particular website is vulnerable for sql injection or not. Not only that, tools like sqlmap will help to display database,tables and data inside them on attacker's computer screen.(At the end of the blog post I am going to show how to get databases using sqlmap).
                      Sql injection is like changing the query according to our way. Assume there is a registration page. When someone fills it and submits data he/she entered should go to the database. Or to a specific table in the database. What attacker does is he modify this process. That means he bypass the original query. Why he does this? maybe in order to access the website as a regular user(unauthorized access) or retrieve others username and passwords. There can be a ton of purposes behind this.

Now let's see how to do sql injection with some examples. I have written some php web pages to do this. As the database I have used MySQL database. In my GitHub profile I uploaded all the webpages and the copy of my database.
GitHub link  https://github.com/sajith01prasad/SQL_injection

Example 01



This is a very simple registration form. In my database I have a table called users. In that I have two fields called username(primary key) and password. When the user submit values for these two fields those values will be stored in users table.When you submitted check the url bar.




You will see the values you provided in the registration form are parsed as query parameters in the url.
When an attacker sees this he tries to do sql injection on this page. How to do it?
It is pretty simple. There has to be a "INSERT into" statement behind the code. Anyone can guess this. But what after that?
So he is the my code.




Check line number 17. Instead of using query() function I used multi_query(). That's because in this example when I do the sql injection I stop this query and try to make a new query. In order to execute multiple queries I have to use that function. Otherwise my injection won't be possible.

Now add this line to username and hit enter. No need to provide password.
a','a');drop table users;";$bypassed="

Go to phpmyadmin and check whether the table you created(users) is still there or not. It is not there. Why is that?

Okay this is our original sql query.
$q = "INSERT INTO users (username, password) VALUES (' $username ', ' $password ')";

Now I will substitute what I entered in the username textbox to $username.

$q = "INSERT INTO users (username, password) VALUES (' a','a');drop table users;";$bypassed="', ' $password ')";

Now you can see why users table got deleted.



Example 02

For this example also use the same webpage.
Now think the attacker knows someone's username and he wants to change that person's password so he can use that profile.

I have two users called Sam and Tom in my users table.




Provide these values.
USERNAME - hacker
PASSWORD - I-am-hacker');UPDATE users SET password = 'I-hacked-you' WHERE username = 'sam';";$dummy="

What will happen? Actually first of all a new account will be created with username "hacker" and password "I-am-hacker". Then he changes the password of user called "sam"to "I-hacked-you".

I will put these two inputs into the original query so you can clearly understand it.

$q = "INSERT INTO users (username, password) VALUES (' hacker', 'I-am-hacker');UPDATE users SET password = 'I-hacked-you' WHERE username = 'sam';";$dummy="')";

Now check your table. You will see something like this.






Example 03

I have this web page called update.php




updateQuery.php









This page helps users to change their password.
Now think attacker doesn't know any username. But still he has the ability to change everyone's password at once. how he does it?

this is our original sql statement.

$q = "UPDATE users SET password  = '$password'  WHERE username  = '$username' ";

Now add these values to the form.
USERNAME - a' OR '1' = '1
PASSWORD - hacked

let's combine statements together like we did earlier.

$q = "UPDATE users SET password  = 'hacked'  WHERE username  = 'a' OR '1' = '1'";

Check the database now.




You can see everyone's password is "hacked".

Example 04

User Example 3 resources for this example as well. Make your users table like this.





Now what we can do if multi_query() function is used here instead of query()?



Assume the attacker knows someone's username. Now he can delete this user from the database.

This is our original query.

$q = "UPDATE users SET password  = '$password'  WHERE username  = '$username' ";

Provide these values to the textboxes.

USERNAME - a';DELETE FROM users WHERE username = 'tom';";$dummy="
PASSWORD - a

$q = "UPDATE users SET password  = 'a'  WHERE username  = 'a';DELETE FROM users WHERE username = 'tom';";$dummy="'";

Check your table now. User tom is deleted.




Example 05

Now we need another table called "games". In this table there should be two columns called name(primary key) and category.






search.php










topGames.php

When the user gives the type (eg-games) in search.php page it displays information relates to that type.







Attacker can use this to retrieve all users' username and password.
There are two ways to do this.
Our original statement is this.

$query="SELECT * FROM $type";

1st method.

TYPE -  users


$query="SELECT * FROM users";




2nd method

TYPE - games UNION select username AS name, password AS category FROM users

$query="SELECT * FROM games UNION select username AS name, password AS category FROM users";





These are very few examples for sql injection. Now what we can do in order to prevent sql injection??

Main countermeasure for this is using prepared statements instead of using dynamic queries.

Example

EnterValues.php







preparedStatement.php

In here I am not directly applying user inputs to the sql query. What I do is first define the query and bind it with parameters. After that I assign values(user inputs) to those parameters. Then I execute the query.

bind_param() - this functions bind parameters to the query. In the first argument we should say what are the datatypes of each parameter. Since username and password both are strings I provide "ss" as the first argument.



I have a user called sam in my database.





Now let's try to do what we did in example 01.


USERNAME -  a','a');drop table userprepared;";$bypassed="

Now check the table.






Now the entire thing I input in the textbox is taken as a one single string.

Therefore using prepared statements in codes we can prevent SQL injection from happening.


SQLMAP

Sqlmap is a tool which helps us to get information about sql databases. Attackers can use this tool for various kind of things. But let's see how we can use sqlmap to get databases.

First of all you have install sqlmap. Go to this link and download sqlmap http://sqlmap.org/
 . If you are using linux operating system or macOS you simple can cd into the folder and run this command.
python sqlmap.py 
[Python should be already installed on your computer] .

 If sqlmap is working you will see something like this. 

 


Then you have to give this command.  

sudo python sqlmap.py -u http://localhost/sql_injection_examples/InsertQuery.php?username=12 --dbs

-u :- tells target this particular URL
--dbs :- This is there to tell sqlmap to view all the databases

When you run that command you will get all the databases in your DBMS.




Now you can see the database I created for these examples "mysqlinjection" is there in the list.

Cheers.!!! Leave a comment if you have any doubt.