“Luhn” Algorithm using ECMAScript 6

Luhn Algorithm (https://en.wikipedia.org/wiki/Luhn_algorithm) is a very popular algorithm among developers. It is mostly used for Credit Card number validations.

The basic idea is you have a set of numbers with length 15 and using these 15 digits you are calculating a check digit for the 16th position.

The Simplified algorithm definition as follows

  • Lets take a sample 15 digit number (123456789123456) and you need to get the check digit and complete the sequence.
  • First you need to reverse the number sequence – 654321987654321
  • You have to take the odd position numbers and need to multiply them by 2 – 12, 8, 4,18,14,10,6,2
  • If the multiplied value is grater than 9, we need to subtract 9 from them. – 3,8,4,9,5,1,6,2
  • The Even number list is not subjected to change – 5,3,1,8,6,4,2
  • We need to add those numbers together and need to get a total

(3+8+4+9+5+1+6+2)+(5+3+1+8+6+4+2) = 67

  • To get the check digit we need to subtract the output value from next 10th multiplier. In our case it is 70

70 – 67 = 3

Lets do this in ECMA6Script way…

Securing sensitive application data in Android devices.

View Presentation

Mobile device security, one of a major topic in the IT industry there days. People are engaging more on mobile devices these days and they find the mobile device as a portable computer in last decade. Since more people using mobile device as there primary communication mechanism, technologists are more eager to develop applications for mobile devices than other devices.

This white paper will focus on these few areas about data and application security in Android

Cryptographic mechanism for securing data

Database encryption – SQLCipher

Database encryption with SQLCipher provides 256 AES encryption for sqlite databases of your Android applications. SQLCipher is a SQLite extention and it is a open source project maintained by guardianproject .

First we look into how the things are practically working. Lets install sqlite3 in your local machine and create a simple database and table and insert some values into that and try to fetch data.

1. Creating a database

$ sqlite3 sqlciphertest.db

2. Then create a table

sqlite> PRAGMA KEY=’testkey′;
sqlite> CREATE TABLE test1(a,b);

3. Lets Insert a sample data

sqlite> INSERT INTO test1(a,b) VALUES (“value1”, “$599”);
sqlite> .quit

4. This is how your database hexdump looks like

$ hexdump sqlciphertest.db

0000000 5153 694c 6574 6620 726f 616d 2074 0033y
0000010 0004 0101 4000 2020 0000 0200 0000 0200
0000020 0000 0000 0000 0000 0000 0100 0000 0400
0000030 0000 0000 0000 0000 0000 0100 0000 0000
0000040 0000 0000 0000 0000 0000 0000 0000 0000
0000050 0000 0000 0000 0000 0000 0000 0000 0200
0000060 2d00 b8f1 000d 0000 0301 00d1 d103 0000
0000070 0000 0000 0000 0000 0000 0000 0000 0000
*
00003d0 2d00 0601 1717 0117 743b 6261 656c 6574
00003e0 7473 7431 7365 3174 4302 4552 5441 2045
00003f0 4154 4c42 2045 6574 7473 2831 2c61 2962
0000400 000d 0000 0301 00f1 f103 0000 0000 0000
0000410 0000 0000 0000 0000 0000 0000 0000 0000
*
00007f0 0d00 0301 1519 6176 756c 3165 3524 3939
0000800

5. Lets do the same thing using sqlcipher

First you need to download the sqlcipher source from gurdianproject github page and compile it using ./configure and make commands.

Once you done that you can find sqlcipher script within your compiled project.

Lets create the same database and table using sqlcipher command

$ ./sqlcipher sqlciphertest2.db

sqlite> PRAGMA KEY=”testkey” ;
sqlite> CREATE TABLE test1(a,b);

6. Then insert some sample data into the table

sqlite> INSERT INTO test1(a,b) VALUES (“value1”, “$599”);

This is how encrypted database hexdump looks like

$ hexdump sqlciphertest2.db

0000000 109b 3ef3 89c5 7511 7030 bdea 0f87 f883
0000010 4180 08ab 2ffc c7a6 a1a1 fe70 d942 843a
0000020 c6e6 0f9a 7052 35b2 0e8e ff29 f251 e90c
0000030 8b6e f232 c0f7 c1b1 7bb6 7d4b ed78 0d27
0000040 cb50 af7b 86a6 a674 fc2d 76bb 87fc 3c25
0000050 12d3 7059 e6c8 c543 cfa5 b6f2 f5c4 02b9
0000060 7a1f c0fd d628 f933 7687 e949 cd08 a83c
0000070 9c33 4124 8714 7b69 3a58 55eb f2e5 1d3f
0000080 8625 dec7 3076 b26e 84be cae8 56d0 348d
0000090 f9c4 78e9 5126 2dee b718 6a20 fc3a 6a08
00000a0 2b4c 26a6 4206 5018 27b0 df7a 1d9a bc0f
00000b0 e3cc bb60 dc98 48a6 d238 81b3 10b6 7870
00000c0 cddc e566 1eb8 b569 d4be e9d3 4d2f 6ad3
00000d0 4ddf 070c 70a7 f0be 3852 13ec 2548 b27a
00000e0 aec7 1f00 869f f2df 3077 e197 9f2b 9021
00000f0 147f cfb5 80d3 1386 dafc 48f5 f06d c6d9
0000100 1195 0b24 b8e3 5118 356b bb79 c591 f4e6
0000110 b069 6604 f1e8 04e1 a5b8 425e 057d f0a7
0000120 0c6a 34d1 50b7 23da 4c49 0040 8cb1 bd76
0000130 6b6b 24eb 0356 4f7a 580c 1e33 7cb9 c810
0000140 a4ac d287 ff71 bf10 4e7e eefb 8d7f 4987
0000150 3e9a d434 21c6 e8f6 39e6 3f9f 758c a3f1
0000160 1515 00a7 02a9 dada 4443 0ca6 643e 1b7b
0000170 ea83 ba30 4d09 a612 e5b9 8510 7ce2 33e3
0000180 172a 5c74 ce84 0056 763c 05a6 d9d3 cea1
0000190 e556 d63e c16f a4c6 d551 2485 335b 94ee
00001a0 2841 ac7d 06dd c526 f875 2e35 1e7a 8388
00001b0 1615 31fb 903b f69c ac78 9962 4712 6c5c
00001c0 e812 545c 2906 821e 7620 895f 15ee 8cad
00001d0 4a05 aba8 e4f0 3ead e107 ce14 656d 5086
00001e0 5bd5 4c81 b766 d3a7 9c69 33fb ee27 7c6a
00001f0 1c34 fdef 3d11 5332 9d17 8daa 9656 6617
0000200 e0e4 6182 40bd a0bb 2b91 0e49 eb4e 8c44
0000210 567c 8540 22e1 6b6d 8eee 7075 d728 5e38
0000220 645e 782b 2924 e65e a0ee 58df cdae 07df
0000230 3236 cb49 137d d86d 228a b027 4f82 688f
0000370 5fad…………

7. Then we try to fetch some data from the encrypted database

sqlite> SELECT * FROM test1;

Error: file is encrypted or is not a database

Now you are created a encrypted database using command line, lets see how you can create a encrypted database using Android code.

Add these four files to your libs directory

sqlcipher.jar,
libdatabase_sqlcipher.so,
libsqlcipher_android.so
libstlport_shared.so

Then you can convert all the android.database.sqlite.* imports to info.guardianproject.database.sqlite.*.

Full-Disk encryption

Full disk encryption will make your devices data unreadable using low-level encryption functions such as dm-crypt, which is the standard disk encryption system in the Linux kernel. The common methods used in Android system to encrypt disk data is PIN, Pattern and password but in Android v5.1 above the encryption is built in

File-based encryption

Android Nougat and onwards supports file based encryption. Each file is encrypted with a different key and decrypted individually

Encrypting and Decrypting With Password-based Keys

Lets have a look at how we can use password based keys to secure your sensitive data. For that we have few guide lines to follow. Thease are the five major things to consider.

1. When you want to generate key from password it is recommended to use salt.

private void createSalt() {

mSalt = new byte[SALT_LENGTH_BYTES];

SecureRandom srand = new SecureRandom();
srand.nextBytes(mSalt);
}

SecretKey secretKey = generateKey(password, mSalt);

2. Encryption mode and padding

private static final String TRANSFORMATION = “AES/CBC/PKCS7Padding”;

Cipher cipher = Cipher.getInstance(TRANSFORMATION);

3. Use strong encryption technologies

cipher.init(Cipher.ENCRYPT_MODE, secretKey);
encrypted = cipher.doFinal(plain);

4. Specify an appropriate hash iteration count

private static final int KEY_GEN_ITERATION_COUNT = 1024;

5. Use a key of length sufficient to guarantee the strength of encryption.

private static final int KEY_LENGTH_BITS = 128;

In some cases, only data encryption will be performed -using a stored public key- on the application

side, while decryption is performed in a separate safe location (such as a server) under a private key.

In cases such as this, it is possible to use public-key (asymmetric-key) encryption.

Encrypting and Decrypting With Public Keys

In this case we are encrypting data in our application side using a public key and the decryption is happening in the server side with the private key. Usually we are using RSA algorithm as a key algorithm here. As a padding rule we can use OAEPPADDING.

In this mechanism, we have to consider main three points

1. Encryption mode and padding

2. Strong encryption method

3. Sufficient key length for strong encryptio

Encrypting and Decrypting Using Pre-Shared Keys

This method is used specially for protecting large data sets , for example application assets. Above three things also applicable for pre shared key encryption as well. Usually we are using AES algorithm as a key algorithm here and CBC as block encryption mode. As a padding rule we can use PKCS7Padding.

1. Encryption mode and padding
2. Strong encryption method
3. Sufficient key length for strong encryption

Securing WebViews and WebView data

WebViews are some what risky component in android applications because it opens the door for lot of security risks of your application as well as your device. The major problem with WebView is it can execute javascript with javascript-java bind. You can enable or disable javascript execution with WebSettings#setJavaScriptEnabled() function.

When you require to use WebView , its better to enable javascript only for your in-house web applications and apk stored contents .You must avoid using javascript enabled WebView for third party applications.

These key rules need to follow if you are suppose to use webview

1. Do not allow accessing files (except res/ or assets)

webSettings.setAllowFileAccess(false);
webSettings.setJavaScriptEnabled(true);
webView.loadUrl(“file:///android_asset/sample/index.html“);

2. Enable javascript only for in-house content.

Your web service can only refer to contents which are managed in-house and you should use HTTPS connections for in-house web services and web pages also you should handle all SSL errors.

webView.setWebViewClient(new WebViewClient() {

@Override

public void onReceivedSslError(WebView view,

SslErrorHandler handler, SslError error) {

});

3. If you need to display not in-house content in your WebView its better disable javascript and handle SSL errors appropriately.

switch (error.getPrimaryError()) {

case SslError.SSL_EXPIRED:
case SslError.SSL_IDMISMATCH:
case SslError.SSL_NOTYETVALID:
case SslError.SSL_UNTRUSTED:
default:
}

Another important concept to consider is disable JavaScript to show URLs which are received through Intent. If you need to show URL which is received from Intent, etc., you have to confirm that URL is in

managed URL in-house. In short, the application has to check URL with white list which is regular

expression, etc. In addition, it should be HTTPS

Common WebView vulnerabilities

1. addJavascriptInterface issue –

If you are suppose to inject java objects through javascript interface avoid using it. It could allow attackers to call native Android methods (Java) via JavaScript on WebView

2.setAllowFileAccessFromFileURLs() issue –

Other than using application assets or res folder files you should not allow other files to access the application stuff . All files that the app has access rights can be accessed to by using the file scheme in web pages regardless of the page origins. For example, a malicious web page could access the files stored in the app’s private directory by sending a request to the uri of a private file of the app with the file scheme. Disable URL file access by set those method to false.

webView = (WebView) findViewById(R.id.webview); webView.setWebViewClient(new WebViewUnlimitedClient()); WebSettings settings = webView.getSettings(); settings.setAllowUniversalAccessFromFileURLs(false); settings.setAllowFileAccessFromFileURLs(false);

‎3. postWebMessage(WebMessage message, Uri targetOrigin) issue –

Do not use wild card origin name as a targetOrigin. If wildcards are specified, the sender origin of the message is not checked, and the message may be sent from any arbitrary origin. In a situation in which malicious content has been read into WebView. Use targetOrigin explicitly to avoid this issue Chrome custom tabs (Chrome multi-process architecture)

Web views are not always a best option when you need fast and secure browsing inside your native application. You can customize web-view to meet the requirement but you may need to have lot of workarounds like UI fixes, security and optimization. Google provides a secured, easy implementation and optimized web component called Chrome custom tabs, in security point of view Google’s Safe Browsing to protect the user and the device from dangerous sites. This very important if you are suppose to load external sites from your Android application.

Using Account manager for authentication and secure data storing

In-house accounts concept

If you want your application keep away from dealing with extremely sensitive data there is a better option for that, it is the Android account manager. Account manager keeps sensitive information like passwords, usernames and tokens in a separated account handling location. When you are creating an in-house accounts there are important few points to consider.

Do not store passwords inside account manager

Implement a service called authenticator and add meta-data resources xml file and includes separate authenticator class on onCreate.

Authenticator class must extends AbstractAccountAuthenticator.

HTTPS protocol must be implemented within Account manager for Web Server communication.

Account information must not logged into files or console.

Using android NDK for sensitive data storing

Android NDK is a good solution for securing sensitive data. Normal java code is easy to decompile using popular tools like Apktool and jadx. But if you use c++ code to write some sensitive code stuff , your application will be hard to decompile but it can be dissembled. Some developers hide their keys in C++ using the Native Developer Kit (NDK). The NDK enables developers to write code as a C++ library. This can be useful if you want to try to hide any keys in binary code.

Lets look at more details about writing c++ library code to secure your sensitive information. As a example use case, we can provide a solutions for

Oath authentication secret key hiding (client id and client secret) in a native function

Encrypting databases using secret key which is stored in native code base.

For developing native applications inside Android Studio, first you need following components

– SDK Patch Applier v4 (patcher;v4)
– LLDB 2.2 – high performance debugger
– CMake 3.6.3155560 (cmake;3.6.3155560) – for building purposes
– NDK (ndk-bundle) , open SDK manager and install them.

In a prvious topic we discussed how to use sqlcipher to encrypt database, here we use both sqlcipher and NDK to secure database key.

But it is recommended to use device specific encrypt key other than using a hard coded value inside your native c++ code.

Step 1: android_id = we hava a c++ method to get android_id

Step 2: Make a string using ndk method to return android BOARD, BRAND, DEVICE, DISPLAY etc. information. This is device specific.

Step 3: device_id = we can get the device MEID using c++ method.

Step 4: Then we hash all three values using md5, this is our device specific encrypt key for database encrypting. String key2 = md5(str1 + device_id + android_id);

Step 5: This is a sample NDK C++ code function to store the database encrypt key. Function getid with calculate the device specific hash and we are going to call this from java side. #include #include jstring Java_com_duminda_sqlndk_MainActivity_secureFunction(JNIEnv* env, jobject javaThis) { return (*env)->NewStringUTF(env, (char *)getid() ); }

Step 6: We can load our ndk function like this. static {System.loadLibrary(“sqlndk”); } private native String secureFunction();

Step 7: we can get out secret key from NDK String sqlkey = secureFunction();

Step 8: As a SQLCiper key, we can use above key. SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, sqlkey, null); Then the database is encrypted using sqlcipher with a well secured encryption key. Overclok’s Kryptonite Obfuscation with Android NDK.

Code obfuscation is a one of best data leak prevention methodology and if you are thinking more about code security there is a more advanced way to obfuscate your resources.

It is possible to write secure code using c++ , compiled with ndk but it is more secure if you can obfuscate the C++ code as well (with ndk and llvm-obfuscator). LLVM(Low Level Virtual Machine) obfuscation allows you to get obfuscated native c++ code and make more secure code which protects your application data and resources.

https://github.com/obfuscator-llvm/

Future of Data and Application security – Biometric Authentication as an application security mechanism

A variety of methods for biological authentication are currently under research and development,with methods using facial information and vocal signatures particularly prominent. Among these methods, methods for using fingerprint authentication to identify individuals have been used since ancient times, and are used today for purposes such as signatures (by thumbprint) and crime

investigation. Applications of fingerprinting have also advanced in several areas of the computer world, and in recent years these methods have begun to enjoy wide recognition as highly convenient techniques (offering advantages such as ease of input) for use in areas such as identifying the owner of a smartphone (primarily for unlocking screens).

Fingerprint Authentication

Android 6.0(API Level 23) incorporates a framework for fingerprint authentication on terminals, which allows applications to make use of fingerprint authentication features to identify individuals. In what follows we discuss some security precautions to keep in mind when using fingerprint authentication.

There are important points to consider when we use fingerprint authentication in Android

1. When creating (registering) keys, use an encryption algorithm that is not vulnerable (meets standards).

Algorithms that meet certain standards adequate to prevent eavesdropping by third parties

2. Restrict encrypted data to items that can be restored (replaced) by methods other than fingerprint authentication

When an application uses fingerprint authentication features for the encryption of data within the app, the app must be designed in such a way as to allow the data to be recovered (replaced) by methods other than fingerprint authentication.

3. Notify users that fingerprint registration will be required to create a key

In order to create a key using fingerprint authentication, it is necessary that a user’s fingerprints be registered on the terminal. When designing apps to guide users to the Settings menu to encourage fingerprint registration, developers must keep in mind that fingerprints represent important personal data, and it is desirable to explain to users why it is necessary or convenient for the app to use fingerprint information.

Information leakage from Android clipboard and prevention

The information which was copied by user or application, is once stored in the buffer called Clipboard. The information stored in Clipboard is distributed to other applications when it is pasted by a user or an application. So there is

a risk which leads to information leakage in this Clipboard function. It is because the entity of Clipboard is single in a system and any application can obtain the information stored in Clipboard at any time by using ClipboardManager. It means that all the information which user copied/cut, is

leaked out to the malicious application.

Prevention

1. Delete copy/cut from the menu when character string selection

TextView.setCustomSelectionActionMODECallback() method cannot be used in before Android 3.0(API Level 11). In this case, the easiest method to prohibit copying/cutting is to disable Long Click

View. Disabling Long Click View can be specified in layout xml file.

uncopyableEdit.setCustomSelectionActionModeCallback(actionModeCallback);

2. Disable Long Click View

Prohibiting copying/cutting can also be realized by disabling Long Click View. Disabling Long Click View can be specified in layout xml file.

android:longClickable=”false”