php – security for android app in communicate with webservice-ThrowExceptions

Exception or error:

I am developing an android app for a site, which I made a capability in it that users can send data to the site database in the app. I use PHP web services and URL in android code for connecting to the web service.
how can I make my app (and my php web service) secure that no one can’t find the web service url by debugging my apk and send amount of data to the site and make the site down.

any tips for make software system secure from these kinds of dangers can help me a lot, thank you.

edit :
for example now I use AsyncTask for sending data in my edittext to webservice like below.
I use this code in my oncreate to send data to AsyncTask class in the name of AskServer() :

link = "http://mywebservice-adrress/name.php";
new AskServer().execute(link, edttext.getText().toString());

and here is my doInBackground of my AsyncTask class :

@Override
    protected Object doInBackground(String... params) {
        BufferedReader buf = null;

        try {
            URL link = new URL(params[0]);
            URLConnection connect = link.openConnection();

            connect.setDoOutput(true);
            OutputStreamWriter osw = new OutputStreamWriter(connect.getOutputStream());
            String data = URLEncoder.encode("field","UTF8") +"="+ URLEncoder.encode(params[1], "UTF8");
            sw.write(data);
            osw.flush();
        } catch (Exception e) {e.printStackTrace();}

        return null;
    }// end doInbackground()

and here is my php code in my web service :

<?php

include 'config.php';
$field=$_POST['field'];


mysql_query("insert into `wp_comments` (`comment_content`)
                    values('$field')");
?>

It is an example and my real code send much more data to server, and maybe code above doesn’t work, I just make my question more exact and specific as stackoverflow want me.
my question is how to make these transactions safe and secure from hackers which may debug my code and find my url , in code above (params[0]) and send amount of data to my site and make it down. or how can I use the service of sending data to server more secure from these kind of dangers??

How to solve:

You cannot hide the endpoint in any way (you can try, but you will fail). If the app can request some URL everybody can. You could have a look at services like cloudflare, but you should look into the actual security of your application instead.

Your question “send amount of data to my site and make it down” doesn’t make much sense in relation to your question. Why would sending data to your server make it go down?

Unless you are asking about how to mitigate (D)DOS attacks which is a whole other level of prevention (with moderate success using expensive services).

What you should worry about more instead is the actual security of your application, e.g.:

$field=$_POST['field'];


mysql_query("insert into `wp_comments` (`comment_content`)
                    values('$field')");

is vulnerable to SQL injection.

Also not shared here, but you could look into authentication for your application’s endpoints using e.g. oAuth so that you don’t have to store username+password in the app itself, but “just” an access token which you can easily revoke.

###

In general, the other answers to your question are correct: it’s difficult to ensure that only your application can make use of your server’s API. The crux of the problem is this: nothing prevents a malicious user from pretending to be your application. Most countermeasures are what is known as “security through obscurity”. Examples include:

  1. Using an undocumented “binary” request format: with enough time, a malicious user can simply reverse-engineer your binary format.
  2. Hiding the address of the API endpoint: malicious user can just sniff the request as it passes from your application through the network that he controls on its way to your server.
  3. Requiring a cryptographic “signature” to be provided on each API request: malicious user can just reverse-engineer your application and find the cryptographic key that is being used. (A technique known as “white box cryptography” tries to make it difficult to extract the key from your application, but it merely slows down a determined adversary.)

There is however one method which could theoretically work with newer Android devices: use the built-in Keystore system, which is designed to prevent malicious users from extracting the cryptographic keys used by your application. Brief overview of what you would need to do:

  1. When your app is first installed, generate a new public/private keypair using the KeyPairGenerator as outlined in the example “NIST P-256 EC key pair for signing/verification using ECDSA”.
  2. Once the keypair has been generated, send the public key to your server, which will store this key in your user database.
  3. When your application wants to make an API call to your server, it needs to sign the request with the private key; and the server needs to verify this signature using the user’s public key. If the request does not have a valid signature or the signature cannot be verified, your server must refuse the request.

No matter what the malicious user does, once step #1 has been completed and the private key is safely stored in the Android device’s Keystore, there is no way to extract that key and use it to impersonate your application. Unfortunately, even this method has a critical weakness: how can you verify that the request in step #1 (where your application registers its secure public key with your server) is being made by your application?

So for all practical purposes, you’ll just have to live with the consequences of exposing an API on your server and take whatever steps you need in order to protect that API from abuse.

###

Security for android app in RESTAPI

We have design a “.so” file for security regarding in RESTAPI “.so” file is native compiled file by android NDK.
We have design a auth_key which is generate by “.so” file according user “email” and “password”. It’s generate 265 digit key for authorization. Means user is valid or not. and also this same algorithm is also apply on server side to get original data from the key. I have see 99% payment gateway is also used our own algorithm for generating auth_key in “.so” means native file. Because any hacker cann’t possible to reverse Engineer this file to get original Algorithm code to generate auth_key

###

Even if you try to hide your String by appending bytes, using chars and what not, ultimately it will still make a network call. Using TCP dump or HTTP proxies such as Charles, your call is intercepted in no-time.

You rather have to focus on protecting the access to your server and possibly look into solutions such as CloudFlare DDOS protection if you are worried that your server will be ddossed.

###

Mobile Application communicating to a server if your using a Web Service first port of call is SSL certificate.

Then use an API system that has a single end point (this means it’s one endpoint for all requests) SOAP or JSON-RPC V2 i prefer the latter for 2 reasons the first is SOAP although it is not supposed to differs between ASP.NET and PHP in the way the enveloping works. and JSON-RPC is a lot smaller payload.

These combined with an an SSL protected single Endpoint means no one can obtain any more that the server address, so you could implement a basic post login for a basic protection but if some one can de-construct your app E.G it’s in Apache Cordova or something i would recommend you use a user login system.

MY FIRST POINT IS THE MOST IMPORTANT USE SSL FOR WEB SERVICES.
this can be WebSockets, SOAP, JSON-RPC, REST anything that goes though a web server.

###

I am always worrying like you. Java decoder, decompilers, dex2jar ,. such software are always threatening application’s code security.

Using webserivce is thought to be good secure enough, because your important data, such as email,ip,password,db name are not necessary to write down in your projects.

But even them can be hacked on url abuse. Such kind can be found on insert and update.
Hackers can found your code to insert or update and they can manually try it on described url with their desired data.

Example –
http://www.myweb.com/update?name=“hacker”&value=”1111111111”

Such kind of cheat can be arise on hacking your application.

I suggest you to create custom encryption and dynamic data –

I mean, You should get the whole url from server/database, not encoded with project.

Example –
http://www.”+web+”/”+v1+”=1212121″
Such kind of complex sentences can make hackers to be frustrated on decoding. Dynamic value can also hard to find and to combine .

Also Try substring to make illusion. and get substring number specifications from dynamic server. That cause hackers to void your app to continue cracking.

This method is useful for me but I’m not sure for everyone.

###

As everyone said, you can’t hide your endpoints. The only way to secure your web service is writing safe code.

In addition to everything already said, i would suggest few tools i found really simple yet powerful for writing a small web service:

###

first,you can change to https,which is safer.

sec,you can make some rule for params from client.

I wrote an easy framework and deal with it like this

`
/**
* check params
*/

private static function checkParams($params){

    $data = $params['data'];
    $str = MD5_PREFIX;
    foreach($data as $k=>$v){
        $str.=$k.$v;
    }
    if(md5($str) != $params['sign']){
        throw new Exception("err sign",SIGN_NOT_CORRECT);
    }
}

`

###

After this time pass I come with some answers with my own question. these tips are for php server side of android app client, but the logic can use in other languages of server side.

Security :
    1- Validate input data
    2- Filter input data
    3- Bind parameters to refuse query injection
    4- Give least access to user
    5- Refuse Leakage info by disableing log and httpd.conf


    6- Output Escaping : 
        escape html in output for sites and useless for webservices
        Functions like : htmlspecialchars()


    Filter      : diagnose XSS characters and filter them
    Validate    : check if input data is like the data type we expect

    Filter functions    :
        strip_tags()
        str_replace()
        preg_replace()
        Force Change DataType by placeing datatype before them : $input = (int) $input;


    Validat functions   :
        stripos()
        preg_match()
        "ctype" functions like : ctype_alnum(text), ctype_alpha(text), ctype_digit(text) : if input is ctype validate type return true else return false

        isset()
        filter_var()


    Access to user :
        initialize all variables before use
        use if and else statements to check everything is ok to prevent showing errors
        try catch for PDO SQL errors
        HASH the password and important data in database
        set hard names for database tables and columns
        make index.php in the folder and use this code :
            <?php
                header('location',HOME_URL);
                exit;
            ?>
        in .htdocs paste this code : Options -Indexes



    Database security :
        $mysqli->real_escape_string($input); // for scape chars like ' " 
        use stored procedures for refuse query injection.
        filter inputs for : stripos($input, 'UNION')

I hope these tips help

Leave a Reply

Your email address will not be published. Required fields are marked *