Thursday, 7 February 2013

Mobile App Security - Top 10

Industry analysts’ findings reveal that in 2011, the number of users to access banking services from their smartphones was a gigantic 300 million, which is further expected to rise to a whopping 530 million by 2013!The exponential growth of smart phones and their widespread usage have brought to the fore the criticality of mobile app security from an enterprise safety standpoint.The rapid adoption of mobile devices and mobile apps has led to a significant and unbounded security risk for any enterprise. The mobile app threat is escalating rapidly – spanning simple “premium SMS and call” attacks that are directly monetized by running up a victim’s bill, to hampering full-scale mobile functionality.

The need for enterprises to equip their mobile workforce with productive, meaningful applications is more critical than ever. Such applications need to ensure the security of sensitive data on the device as well as internal networks. Enterprise mobile applications extend corporate networks beyond the perimeter devices, thus potentially exposing these organizations to new types of security threats.

As smartphones are natural devices for data management, they are easy sources of sensitive data like credit card numbers, authentication information, private information, activity logs (calendar, call logs) and the like. The graphic below shows the relevant statistics about types of information stored by users in mobile devices.
Survey carried out by ESET Latin America(Trends for 2013)

Three prime target components for attackers are – Data, Identity and Availability.

Android platform remains the prime target for both mobile malware and spyware miscreants. According to one of McAfee’s recent findings, there are very few mobile threats that are not directed at Android phones!After an apparent but slight decline earlier in the year, Android malware has rebounded and has almost doubled.
McAfee Threats Report: Third Quarter 2012


Here's peek into 10 key inhibitors for enterprise apps - 

    1: Insecure Data Storage

Most mobile applications have a need to store sensitive information, either in its local storage or on SD card. The information might be passwords, account records, or proprietary information.
Frequently, encryption techniques are used to protect this sensitive information. While encryption has become relatively easy to implement and use, developers still frequently make mistakes while integrating it. Developers may overestimate the protection gained by using encryption and not be as careful in securing other aspects of the mobile application.
A few areas where mistakes are commonly made include:
         Sensitive data left unprotected.
         Weak or global permissions
  • Insecure storage of keys, certificates, and passwords
  • Improper storage of secrets in memory
  • Poor sources of randomness
  • Poor choice of algorithm
  • Attempting to invent a new encryption algorithm
  • Failure to include support for encryption key changes and other required maintenance procedures
The impact of these weaknesses can be devastating to the security of a mobile.
Prevention Tips
         Store ONLY what is absolutely required
         Never use public storage areas (i.e. SD card)
         Leverage secure containers and platform provided file encryption APIs.
         Do not grant files world readable or world writable permissions
         Do not store historical GPS/tracking or other sensitive information on the device beyond the period required by the application
         There is currently no standard secure deletion procedure for flash memory (unless wiping the entire medium/card). Therefore data encryption and secure key management are especially important.

     2: Weak Server Side Controls

Weak server controls applies on backend systems causing loss of data via cloud storage. The majority of mobile applications interact with the backend APIs using REST/Web Services or proprietary protocols. Insecure implementation of backend APIs or services, and not keeping the back-end platform hardened/patched will allow attackers to compromise data on the mobile device when transferred to the backend, or to attack the backend through the mobile application.
These are:
         Not mobile specific, but essential to get right
         Applicable to backend service
Prevention Tips
         Carry out a specific check of your code for sensitive data unintentionally transferred, any data transferred between the mobile device and web-server back- ends and other external interfaces - (e.g. is location or other information included within file metadata).
         Ensure that the backend platform (server) is running with a hardened configuration with the latest security patches applied to the OS, Web Server and other application components.
         All backend services (Web Services/REST) for mobile apps should be tested for vulnerabilities periodically, e.g. using static code analyzer tools for testing and finding security flaws.
         Ensure adequate logs are retained on the backend in order to detect and respond to incidents and perform forensics (within the limits of data protection law).
         Understand the additional risks mobile apps introduce into existing architecture.

      3: Insufficient Transport Layer Protection

Network spoofing attacks, surveillance. The majority of smart phones are capable of using multiple network mechanisms including Wi-Fi, provider network (3G, GSM, CDMA and others), Bluetooth etc. Sensitive data passing through insecure channels could be intercepted.
These can be due to:
         Complete lack of encryption for transmitted data
         Weakly encrypted data in transit
         Authorization header sent over HTTP
         Strong encryption, but ignoring security warnings
         Ignoring certificate validation errors
         Falling back to plain text after failures
Prevention Tips
         Assume that the provider network layer is not secure. Modern network layer attacks can decrypt provider network encryption, and there is no guarantee that the Wi-Fi network will be appropriately encrypted.
         Applications should enforce the use of an end-to-end secure channel (such as SSL/TLS) when sending sensitive information over the wire/air (e.g. using Strict Transport Security - STS).This includes passing user credentials, or other authentication equivalents. This provides confidentiality and integrity protection.
         Use strong and well-known encryption algorithms and appropriate key lengths.
         Be very cautious in allowing self- signed certificates. Do not disable or ignore SSL chain validation.
         SMS, MMS or notifications should not be used to send sensitive data to or from mobile end-points.
         When security exceptions are thrown, it’s generally for a reason… DO NOT ignore them!

     4: Client Side Injection

This type of attack exploits buffer overflow vulnerability in targeted client software through injection of malicious content from a custom-built hostile service.
The server may look like a valid server, but in reality it may be a hostile server aimed at fooling the client software. For instance the server can use honey pots and get the client to download malicious code.
The hostile server may also attempt to install and run malicious code on the client software. That malicious code can be used to scan the client software for buffer overflow.
Attack Execution Flow:
         The attacker creates a custom hostile service
         The attacker acquires information about the kind of client attaching to her hostile service to determine if it contains exploitable buffer overflow vulnerability.
         The attacker intentionally feeds malicious data to the client to exploit the buffer overflow vulnerability that she has uncovered.
         The attacker leverages the exploit to execute arbitrary code or to cause a denial of service.

These attacks generally occur in apps using browser libraries:
         Pure web apps
         Hybrid web/native apps
Also, mobile attackers can:
         Abuse phone dialer +SMS
         Abuse in-app payments
Prevention Tips
         Sanitize/Escape un trusted data before rendering or executing it
         Use prepared statements for database calls
         Minimize the sensitive native capabilities tied to hybrid web functionalities

       5: Poor Authorization and Authentication

This is part mobile, part architecture threat. Unauthorized individuals may obtain access to sensitive data or systems by circumventing authentication systems (logins).
This can result in unauthorized access and loss of confidential data.
Prevention Tips
         Implement user authentication/authorization and session management correctly
         Use authentication that ties back to the end user identity (rather than the device identity).
         Never use device ID or subscriber ID as sole authenticator.
         Use context to add security to authentication - e.g. IP location, etc...
         Authenticate all API calls

     6: Improper Session Handling

Unauthorized individuals may obtain access to sensitive data by reusing valid tokens or cookies.
Mobile app sessions are generally MUCH longer due to the convenience and reusability. Apps maintain sessions via:

         HTTP cookies
         OAuth  tokens
         SSO authentication services

In case of mobile apps it’s always a bad idea to use a device identifier as a session token. This can lead to unauthorized access and circumvent licensing and payments.

Prevention Tips
         It is important to ensure that the session management is handled correctly after the initial authentication, using appropriate secure protocols. For example, require authentication credentials or tokens to be passed with any subsequent request (especially those granting privileged access or modification).
         Don’t be afraid to make users re-authenticate every so often
         Ensure that tokens can be revoked quickly in the event of a lost/stolen device
         Utilize high entropy, tested token generation resources

     7: Security Decisions via Un-trusted Inputs

Data leakage. Users may install applications that may be malicious and can transmit personal data (or other sensitive stored data) for malicious purposes. It can also be leveraged to bypass permissions and security model resulting in confidentiality loss and unauthorized consumption of paid resources.

Prevention Tips
         Check caller’s permissions at input boundaries

         Vet the security/authenticity of any third party code/libraries used in your mobile application (e.g. making sure they come from a reliable source, with maintenance supported, no back-end Trojans)

         Pay particular attention to validating all data received from and sent to non-trusted third party apps (e.g. ad network software) before processing within the application.

         Track all third party frameworks/APIs used in the mobile application for security patches. A corresponding security update must be done for the mobile applications using these third party APIs/frameworks.

     8: Side Channel Data Leakage

This is generally a result of mix of not disabling platform features and programmatic flaws. Generally sensitive data ends up in unintended places like:

         Web caches
         Keystroke Logging
         Screenshots
         Logs (system, crash)
         Temp directories

Also, there is a need to understand what 3rd party libraries are doing with user data (i.e. ad networks, analytics)

Prevention Tips
         Never log credentials, or other sensitive data to system logs
         Remove sensitive data before screenshots are taken, disable keystroke logging per field, and utilize anti-caching directives for web content
         Debug your apps before releasing them to observe files created, written to, or modified in any way
         Carefully review any third party libraries you introduce and data they consume
         Test your applications across as many platform versions as possible

     9: Broken Cryptography

These are the result of broken implementations using strong crypto libraries or custom (easily defeated) crypto implementation.

Always keep in mind:
         Encoding != Encryption
         Serialization != Encryption

Prevention Tips
         Never store key with encrypted data, it negates everything
         Leverage battle-tested crypto libraries vice writing your own
         Take advantage of what your platform already provides. Utilize file encryption APIs
         Leverage secure containers

     10: Sensitive Information Disclosure

Unsafe sensitive data storage, attacks on decommissioned phones unintentional disclosure: Mobile devices (being mobile) have a higher risk of loss or theft. Adequate protection should be built in to minimize the loss of sensitive data on the device.

Commonly found “treasures” are:
         API keys
         Passwords
         Sensitive business logic

Prevention Tips
         In the design phase, classify data storage according to sensitivity and apply controls accordingly (e.g. passwords, personal data, location, error logs, etc.). Process, store and use data according to its classification. Validate the security of API calls applied to sensitive data.
         Store sensitive data on the server instead of the client-end device. This is based on the assumption that secure network connectivity is sufficiently available and that protection mechanisms available to server side storage are superior.
         When storing data on the device, use a file encryption API provided by the OS or other trusted source. Some platforms provide file encryption APIs which use a secret key protected by the device unlock code and deleteable on remote kill. If this is available, it should be used as it increases the security of the encryption without creating extra burden on the end-user. It also makes stored data safer in the case of loss or theft. However, it should be born in mind that even when protected by the device unlock key, if data is stored on the device, its security is dependent on the security of the device unlock code if remote deletion of the key is for any reason not possible.
         Do not store/cache sensitive data (including keys) unless they are encrypted and if possible stored in a tamper-proof area
         Do not store historical GPS/tracking or other sensitive information on the device beyond the period required by the application






Monday, 4 February 2013

Create a batch file (.bat) to invoke a web URL

A batch file contains a series of DOS commands, and is commonly written to automate frequently performed tasks. Instead of typing the same commands over and over, you can simply double-click the batch file or it can be scheduled in server machines.

Batch file can be easily created by creating a simple text file and renaming it to filename.bat
Below are the simple steps -

Open a notepad
Type the following
start iexplore http://saurabh-shubham.blogspot.in/
Save the notepad as batch.bat and run it.
If you want to more sites repeat the same step again like...
start iexplore http://www.yahoo.com
start iexplore http://www.google.com
start iexplore http://www.gmail.com

In my case, I wanted to invoke a web service, wait/pause for some time to execute it and finally close the browser. Here are my lines in blue -
start chrome http://someservice.svc :- Instead of IE, I prefer chrome.
PING 127.0.0.1 -n 6 :- This will ping the local server for 5 seconds. By that time my service gets executed.

taskkill /f /IM chrome.exe :- Finally kill the process to close the browser.

Wednesday, 23 January 2013

Minimal web.config for WCF web service in .Net 4.0

Getting correct configuration for running WCF is important, and I am used to mess with ABCs of WCF web service.
I struggled a lot to get this minimal configuration for web.config and finally I got a working solution. Hope this works for everyone.

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
    <authentication mode="Windows"/>
  </system.web>
  <system.serviceModel>
    <bindings>
    </bindings>
    <services>
      <service name="MyProject.Service">
        <endpoint address="" behaviorConfiguration="webHttp" binding="webHttpBinding"
          contract="MyProject.IService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Tuesday, 15 January 2013

Upload file from device to server using PhoneGap

I have implemented this in Android and it works really well. You may need to customize client side implementation little as per you requirement and it should work fine.
Since we dont have file structure in iPhone, I am not sure how to implement it in iPhone.

 1. Client(device) side implementation
PhoneGap provides file transfer API to transfer file to server, PHP is recommended for server implementation.

function uploadFile() {
   window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
   var directoryReader = fs.root.createReader();
   directoryReader.readEntries(function(entries) {
   imageURI=entries[0].toURI(); // Selected File path
   var options = new FileUploadOptions();
   options.chunkedMode = false;
   options.fileKey="file";
   options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
   alert(options.fileName);
   options.mimeType="text/plain";
   var params = new Object();
   params.value1 = "test";
   params.value2 = "param";
   options.params = params;
   var ft = new FileTransfer();
   ft.upload(imageURI, "ServerIP/Upload.php", win, fail, options,true);
   }, function (error) {
      alert(error.code);
   })}, function (error) {
      alert(error.code);
   });
}

function win(r) {
   alert("success");
   alert("Sent = " + r.bytesSent);
}

function fail(error) {
   alert("error");
   switch (error.code) {
     case FileTransferError.FILE_NOT_FOUND_ERR:
        alert("Photo file not found");
        break;
     case FileTransferError.INVALID_URL_ERR:
       alert("Bad Photo URL");
       break;
     case FileTransferError.CONNECTION_ERR:
       alert("Connection error");
       break;
   }
   alert("An error has occurred: Code = " + error.code);
}

2. Server side implementation
Create a php page(Upload.php) and host it in IIS

<?php
if ($_FILES["file"]["error"] > 0) {
  echo "Return Code: " . $_FILES["file"]["error"] . "";
} else {
  echo "Upload: " . $_FILES["file"]["name"] . "";
  echo "Type: " . $_FILES["file"]["type"] . "";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb";
  echo "Temp file: " . $_FILES["file"]["tmp_name"] . "";
  if (file_exists("D:/PHPUPLOAD/" . $_FILES["file"]["name"])) {
    echo $_FILES["file"]["name"] . " already exists. ";
  } else {
    move_uploaded_file($_FILES["file"]["tmp_name"], "C:/PHPUPLOAD/" . $_FILES["file"]["name"]); //Save location
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  }
}
?>
For example: Create a php file(Upload.php) at – C:\inetpub\wwwroot

Saturday, 5 January 2013

THE RIGHT TO INFORMATION ACT, 2005

Today, I am fed up of BSNL service(I am receiving phone bills from past five months without having a connection ) and I am going to file a RTI for it, and therefor thought that it will be useful for others if I document the procedure of filing RTI. Simply because the more people know about RTI and actively use it, the more each one of us are doing our bit to curb corruption and wrong practices in Government Department. 
In simple words, the Right to Information Act or RTI is an act that practically supports and enables citizens to claim their right to information which is guaranteed by the constitution of India.

Below is the step by step systematic procedure to file RTI application correctly -

1. First you need to get the Information about the concerned public authority who is known as PIO (Public Information Officer ), every organization has a PIO and their address can be found on their website.If you do not get details of PIO at their website or PORTAL just visit the nearest office of the relevant organization or public authority and get the address of PIO.

2. Write an application with “Subject: Application under the RTI Act, 2005” . Mention your query point-wise. Find sample RTI Applications for various problems here.

3. There is a nominal fees of Rs 10 for filing RTI which can be through Postal Order/ CRF or by Bank Draft. It should be in favor of Accounts Officer of particular organization. For example, if RTI for SBI Bank, it should be Accounts Officer, SBI payable at location of concerned department of PIO. For my case, it was BSNL. I paid the fees through postal order which can be easily purchased from any post office. It should look something like below -


4. You may send it by any mean like post, speed post etc. but not by courier. I prefer registered post.

5. You must sign the application form.

6. Finally Acknowledgement: All RTI applications have to be answered in 30 days by respected PIO or Organization.One need to preserve the application number and date of filing or photocopies for future reference.

Get you basic questions answered here. For more information refer RTI GUIDE / HANDBOOKS.

Exercise your Right to Information now!


Friday, 28 December 2012

Commonly asked database Q&A

What is the difference between a “where” clause and a “having” clause?
“Where” is a kind of restriction statement. You use where clause to restrict all the data from DB.Where clause is using before result retrieving. But Having clause is using after retrieving the data.Having clause is a kind of filtering command.

What is bit data type and what’s the information that can be stored inside a bit column?
Bit data type is used to store Boolean information like 1 or 0 (true or false). Until SQL Server 6.5 bit data type could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit data type can represent a third state, which is NULL.

What’s the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it will not log the deletion of each row, instead it logs the de-allocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

 What is de-normalization and when would you go for it?
As the name indicates, de-normalization is the reverse process of normalization. It is the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

What is a “constraint”?
A constraint allows you to apply simple referential integrity checks to a table. There are four primary types of constraints that are currently supported by SQL Server:
PRIMARY/UNIQUE – enforces uniqueness of a particular table column.
DEFAULT – specifies a default value for a column in case an insert operation does not provide one.
FOREIGN KEY – validates that every value in a column exists in a column of another table.
NOT NULL – constraint which does not allow values in the specific column to be null. And also, it is the only constraint which is not a table level constraint.

What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a non-clustered index by default. Another major difference is that, primary key does not allow NULLs, but unique key allows one NULL only.

What is a “functional dependency”? How does it relate to database table design?
Functional dependency relates to how one object depends upon the other in the database. for example, procedure/function sp2 may be called by procedure sp1. Then we say that sp1 has functional dependency on sp2.

Why can a “group by” or “order by” clause expensive to process?
Processing of “group by” or “order by” clause often requires creation of Temporary tables to process the results of the query, which depending of the result set can be very expensive.

Source - GeekyFry

Monday, 24 December 2012

Read/Write files from SD Card – PhoneGap/HTML/Javascript

Javascript functions to list out the files in SD card and show it in html div tag
 
Read files
 function BrowseFile()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
var directoryReader = fs.root.createReader();
directoryReader.readEntries(function(entries) {
var i;
document.getElementById('dirList').innerhtml='';
var child="";
for (i=0; i<entries.length; i++) {
child=child+"<div>"+entries[i].toURI()+"</div>";
alert(entries[i].toURI());
}
document.getElementById('dirList').innerHTML = child;
}, function (error) {
alert(error.code);
})
}, function (error) {
alert(error.code);
});
} 
 
Create a file and write to it
function writeFile()
{
// root file system entry
var root = getFileSystemRoot();
// writes a file
write_file = function(writer)
{
var lineCount = 1;
// set the callbacks
writer.onwritestart = onFileEvent;
writer.onprogress = onFileEvent;
writer.onwrite = onFileWrite;
writer.onabort = onFileEvent;
writer.onerror = onFileError;
writer.onwriteend = function(event)
{
onFileEvent(event);
lineCount += 1;
if (lineCount <= 3)
{
// append a new line
writer.write('Line ' + lineCount + '.\r\n');
}
else {
alert(writer.fileName + ' length=' + writer.length + ', position=' + writer.position);
}
}
// append
writer.seek(writer.length);
// write to file
writer.write('Line ' + lineCount + '.\r\n');
},
// creates a FileWriter object
create_writer = function(fileEntry)
{
fileEntry.createWriter(write_file, onFileSystemError);
};
// create a file and write to it
root.getFile('bbgap2.txt', {create: true}, create_writer, onFileSystemError);
}

Reference links -
http://geekyfry.com/tech-it/smartphones/phonegap/reading-writing-files-from-sd-card-phonegaphtml5javascript/

Loading spinner overlay for hybrid/mobile web applications

Below is the spinner I have implemented in one of my projects. Below are the components you need to place in your respective Javascript, Cs...