21

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??

Mohad Hadi
  • 1,826
  • 3
  • 24
  • 39
  • 1
    I like your question. But, it is not really appropriate for SO. The community is here to help you get *specific* answers to *specific* questions, usually when you have code that is giving you problems. – Reed Oct 29 '15 at 23:52
  • 1
    And you absolutely can't. If the URL is in your app, the the URL can be found by unpacking the apk and decompiling it, no matter how much you try to obscure it. What you need is to ensure that anyone sending a request is authorized, which you will need to do by transferring authorization tokens between the Android app and the server. What you need is something along the lines of "Secure login to php database from Android app" – Reed Oct 29 '15 at 23:55
  • I have added pieces of my code, I think now it's more specific. – Mohad Hadi Oct 30 '15 at 09:24
  • I think this question is too broad. I started to answer it but it just got too long. Can't vote to close :( – james Nov 10 '15 at 22:03

9 Answers9

11

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.

Community
  • 1
  • 1
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • There basically just needs to be a secure way for users to log in to the server from the app (which I would use oAuth for), then (I believe) on subsequent requests (API calls), the oAuth access token (sent by the app) can be validated through server-side HTTP Requests. – Reed Nov 17 '15 at 13:15
  • can I secure my app for sql injection by adding this code after sending data to server : Html.fromhtml(edttxt.getText().toString()).toString(); – Mohad Hadi Nov 18 '15 at 13:28
  • No. That is not related to SQL injection prevention in any way. – PeeHaa Nov 18 '15 at 13:30
  • than how can I prevent users send scripts to webservice? – Mohad Hadi Nov 18 '15 at 13:40
  • 1
    Sending script is another problem than sql injection. SQL injection can be prevented by using prepared statement and bound parameters. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – PeeHaa Nov 18 '15 at 13:45
5

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.

kiwidrew
  • 3,063
  • 1
  • 16
  • 23
2

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

Ramkailash
  • 1,852
  • 1
  • 23
  • 19
  • 4
    "Because any hacker cann't possible to reverse Engineer this file to get original Algorithm code to generate auth_key" what is preventing me from disassembling the so? – PeeHaa Nov 16 '15 at 15:42
  • 1
    A determined individual can reverse engineer anything. – Reed Nov 17 '15 at 13:08
  • Only for java code can by reverse engineer. But we cannot able to reverse engineer "C file". Because it's compile using address no one can get original code after compiled from NDK – Ramkailash Nov 17 '15 at 13:14
  • It very much is perfectly possible. Using IDA pro is one way – PeeHaa Nov 17 '15 at 13:34
  • ProGard is also available for hiding code in android app – Ramkailash Nov 18 '15 at 09:02
  • REST Full is not the best API for as every call has it's own endpoint and you can't hide it... – Barkermn01 Nov 24 '15 at 00:11
  • 2
    I might also ask where does the term `disassemble` come from in programming oh what that would be getting asembly code so no they can't get the original but they can just read the ASM and work it out these people are that skilled they have cracked, audio & video watermarks, about 20 years of developing methods in games and it all gets cracked. nothing on a computer is 100% secure – Barkermn01 Dec 01 '15 at 11:03
  • If I intercept this call I obtain this 265 digit key and can authorize any future call. Reverse engineering is a thing as well. – Gooey Jan 20 '16 at 22:54
  • @Martin I agree.But it's more secure to other compare. – Ramkailash Jan 25 '16 at 06:08
1

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.

Gooey
  • 4,740
  • 10
  • 42
  • 76
1

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.

Barkermn01
  • 6,781
  • 33
  • 83
0

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.

Leonar Aung
  • 187
  • 9
  • 3
    "Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break." – PeeHaa Nov 16 '15 at 15:45
  • Yes, it is just simple idea and how you think on it. Not good or not bad ? @PeeHaa – Leonar Aung Nov 16 '15 at 15:56
  • 1
    that is still merely security by obscurity, which is really not security at all. a determined individual could decode it just with time. – Reed Nov 17 '15 at 00:57
  • Java Decompiling is bad but the worst thing to do for a secure app is using Cordova/Phonegap or something like that where all your communication source is left perfectly intact in the app to the point you can just change the extension of both `IPA` or `APK` to `ZIP` and obtain all your JavaScript code. so your "complex" sentences some one can just read the encryption code and reverse it... – Barkermn01 Nov 24 '15 at 12:54
  • I know this method is not 100% secure enough but you should also know every approach is not 100% secure. This method is creating complex sentences, such variable from dynamic database, some from sum of clicks, some from date, all combining together and substring it again. As complex as your code is , there is a little chance to cross it over. We are not deciding to write down all of code in .java. Providing essential parts from database and getting from dynamic calculating. @ Martin Baker / / Thank you. – Leonar Aung Nov 24 '15 at 15:52
0

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:

Alberto Dallaporta
  • 1,382
  • 1
  • 11
  • 23
0

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);
    }
}

`

rain
  • 243
  • 1
  • 8
0

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

Mohad Hadi
  • 1,826
  • 3
  • 24
  • 39