Saturday, 2 July 2016

How to add Eclipse Code Formatter file in Android Studio

Background

For those who have used Eclipse before know we can supply a formatter file that can be used to format the code you write. But Android studio does not seem to provide that functionality. In this post we will see how we can use the same formatter file in Android Studio.

How to add Eclipse Code Formatter file in Android Studio

  • Go to Plugins section in Studio. Shortcut is Ctrl + Shift + A and then type plugin.

  • Next in the plugins window go to -> "Browse Repositories".

  • Now search for "Eclipse code formatter" and install it.

  • Post install you will need to restart Studio to activate the plugin. After restart go to preferences and search for formatter , you should see eclipse formatter in the search results. Select it and provide your formatter.

  • That's is! You can then format your code and this formatter will be used.

Sunday, 26 June 2016

Certificate Pinning in Android

Background

Generally what happens in a https connections is that client asks for SSL certificate from the SSL compliant server it is communicating with over https. Server will provide a certificate from it's key store. After client receives this certificate it validates it's credentials depending on whether

  • hostname is same as requested
  • has a verifiable chain of trust back to a trusted (root) certificate [from clients trust store]

Now if connections are proxied and you can get the device to trust your (rogue) root CA certificate then you can intercept the secure connections. This is essentially man-in-the-middle attack. Now here is what happens in SSL pinning which potentially adds an extra security layer from man-in-the-middle attacks-

App bundles the known server certificates with it. When app tries to make a secure connection with the server, it validates the certificate received by the server with the ones it has bundled with. So even if OS validates the received certificate chain against a (potentially rogue) root CA, the app will reject the connection displaying network error.

Common type of certificates

In summary, there are four different ways to present certificates and their components:

  1.  PEM Governed by RFCs, it's used preferentially by open-source software. It can have a variety of extensions (.pem, .key, .cer, .cert, more)
  2. PKCS7 An open standard used by Java and supported by Windows. Does not contain private key material.
  3. PKCS12 A private standard that provides enhanced security versus the plain-text PEM format. This can contain private key material. It's used preferentially by Windows systems, and can be freely converted to PEM format through use of openssl.
  4. DER The parent format of PEM. It's useful to think of it as a binary version of the base64-encoded PEM file. Not routinely used by much outside of Windows.

NOTE :
PEM on it's own isn't a certificate, it's just a way of encoding data. X.509 certificates are one type of data that is commonly encoded using PEM.

PEM is a X.509 certificate (whose structure is defined using ASN.1), encoded using the ASN.1 DER (distinguished encoding rules), then run through Base64 encoding and stuck between plain-text anchor lines (BEGIN CERTIFICATE and END CERTIFICATE).

You can represent the same data using the PKCS#7 or PKCS#12 representations, and the openssl command line utility can be used to do this.

Convert a PEM-formatted String to a java.security.cert.X509Certificate

public static X509Certificate parseCertificate(String certStr) throws CertificateException{

    //before decoding we need to get rod off the prefix and suffix
    byte [] decoded = Base64.decode(certStr.replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, ""));

    return (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
}



How to get PEM certificate of the SSL/https compatible site

  1. Go to that particular website  on your browser. Lets say we go to - 
    • https://www.ssllabs.com/
  2. Now look at the top left of the URL bar. You should see details of the connection. And certificate details if your connection is https -


  3. Next click on view certificate and click on Details -

  4. Now click on Export and save your file is PEM format -


You can find the complete Android code on my github repository -
Also you can find app for this ready in playstore -

Related Links

Monday, 20 June 2016

Unprotected private key file error while connecting to AWS via SSH

Background

In one of the previous posts we saw how to connect to your AWS instance.
In that post we saw how you can remotely connect to your instance using ssh (putty on windows). Recently I migrated to mac and got following error for connecting.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0777 for 'Documents/Softwares/athakur-securekey.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: Documents/Softwares/athakur-securekey.pem
Permission denied (publickey).


See screenshot below -

So how do you resolve this?

Solution

You need to give read/write permission just to that user (no groups or other user). So running following command should suffice -
  • chmod 666 athakur-securekey.pem
OR alternatively
  • chmod u=rw athakur-securekey.pem 
  • chmod go=  athakur-securekey.pem



Quoting from AWS documentation -
  • Use the chmod command to make sure your private key file isn't publicly viewable. For example, if the name of your private key file is my-key-pair.pem, use the following command:
    • chmod 400 /path/my-key-pair.pem

Related Links

Saturday, 18 June 2016

Use of final local variables in Java

Background

We know why we declare a instance variable or class or a method as final. So that it cannot be extended or modified or overridden. But there are instances when we declare final local variables i.e declare variables inside method as final. Why would we do that? Let's see that.

To understand the usage I had asked this very question on Stack Overflow and Jon Skeet had answered it which made sense - 

There's one important "feature" of final local variables: they can be used in local (typically anonymous) inner classes. Non-final local variables can't be. That's the primary use of final for local variables, in my experience.

public void foo() {
    final String x = "hello";
    String y = "there";

    Runnable runnable = new Runnable() {
        @Override public void run() {
            System.out.println(x); // This is valid
            System.out.println(y); // This is not
        }
    };
    runnable.run();
}


Note that as a matter of style, some people like to use final even when they're not capturing the variable in a local inner class. I'd certainly be comfortable with final being the default, but a different modifier for "non-final", but I find that adding the modifier explicitly everywhere is too distracting.

NOTE : Well behind the scenes, the compiler generates an instance variable in the anonymous inner class and copies the value of the original variable when the instance is created. 

Java 8 Changes

The compiler is generating a class file from your inner class. A separate class has no way to refer to local variables. If the local variable is final ,Java can handle it by passing it to the constructor of the inner class or by storing it in the class file. If it weren’t effectively final, these tricks wouldn’t work because the value could change after the copy was made. 

Up until Java 7, the programmer actually had to type the final keyword. In Java 8, the “effectively final” concept was introduced. If the code could still compile with the keyword final inserted before the local variable, the variable is effectively final. 

Note same applies for Lambda expressions. To use a local variable in a lambda expression it needed to be final or effectively final.

As far as performance is considered there should not be much difference as JVM does it's own optimizations depending on the usage in code.

Nested classes in Java Summary


Related Links

Friday, 17 June 2016

Iterator Design Pattern

Background

In one of the previous posts we saw Introduction to Design Patterns. In that we learned how different design patterns solve some pre identified design concerns and provide a good solution. Above post also states types of design patterns and links to design patterns we have already covered. In this post we will see another design patter - Iterator pattern. Is it same as the iterator I use to iterate over collections? Yes it is! And that a design pattern? What problem does that solve? Hold on to that we will come there in some time :)



Problem

Lets say there are two companies - Company A and company B. They both maintain employee records for their respective employees and their implementation is something like below - 

Company A Employee records - 

/**
 * 
 * @author athakur
 *
 */
public class CompanyAEmpRecords {

    private Employee[] companyEmployees = new Employee[10];
    private int index = -1;

    public void addEmployee(Employee newEmployee) {
        if (index == 10) {
            throw new RuntimeException("Maximum employee limit reached");
        }
        companyEmployees[index++] = newEmployee;
    }

    public void removeEmployee(String name) {
        // implementation to remove employee
    }

    public int getNoOfEmployees() {
        return index + 1;
    }
    
    public Employee[] getEmployees() {
        return companyEmployees;
    }

}

Company B Employee records - 

/**
 * 
 * @author athakur
 *
 */
public class CompanyBEmpRecords {
    private List<Employee> companyEmployees = new ArrayList<>();

    public void addEmployee(Employee newEmployee) {
        companyEmployees.add(newEmployee);
    }

    public void removeEmployee(String name) {
        // implementation to remove an employee based on name
    }

    public int getNoOfEmployees() {
        return companyEmployees.size();
    }
    
    public List<Employee> getEmployees() {
        return companyEmployees;
    }

}

Life was all good when they were working independently. Company A was small and sufficient with less than 10 employees where as Company B did not really care how many employees joined. But then one day they decided to merge and expand their business. Employees of both the companies will now be under one entity and the task to create code that lists down both company's employees now rests on you. You know both Employee record implementation of companies. So you start writing code using it.


/**
 * 
 * @author athakur
 *
 */
public class CompanyRecordsPrinter {
    
    public void pringCompanyEMployeeRecords(CompanyAEmpRecords companyAEmpRecords, CompanyBEmpRecords companyBEmpRecords) {
        
        Employee[] companyAEmployees = companyAEmpRecords.getEmployees();
        for(int i=0; i< companyAEmpRecords.getNoOfEmployees();i++) {
            System.out.println(companyAEmployees[i]);
        }
        
        List<Employee> companyBEmployees= companyBEmpRecords.getEmployees();
        for(Employee emp : companyBEmployees) {
            System.out.println(emp);
        }
        
    }

}

Well that serves the purpose. We are printing employees in both companies using their records. But is it a good design. Two loops for two different types of data structures. What if Company C is merged with this later. Add a new loop to handle it? Naah. Something does not feel right. This is where iterator pattern comes into picture.

Iterator Pattern defined

The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing it's underlying representation.

Solution

You will basically have a common interface called Iterator which will have methods like -
  • boolean hasNext()
  • Object next()
Each Employee Record class will have a method called getIterator() that will basically return corresponding new instance of Iterator. Lets call it -
  • CompanyAEmpRecordsIterator
  • CompanyBEmpRecordsIterator
Then you can have a common method that take an Object of type Iterator and iterate over it using hasNext() method and get the actual data using next() method.

Sample code -

public class CompanyAEmpRecords implements CompanyEmpRecords {

    private Employee[] companyEmployees = new Employee[10];
    private int index = -1;

    @Override
    public void addEmployee(Employee newEmployee) {
        if (index == 9) {
            throw new RuntimeException("Employees limit reached");
        }
        companyEmployees[++index] = newEmployee;
    }

    @Override
    public void removeEmployee(Employee oldEmployee) {
        int i = 0;
        for (; i <= index; i++) {
            if (companyEmployees[i].equals(oldEmployee)) {
                break;
            }
        }
        for (int j = i; j <= index - 1; j++) {
            companyEmployees[j] = companyEmployees[j + 1];
        }
        companyEmployees[index] = null;
        index--;

    }

    @Override
    public int getNoOfEmployees() {
        return index + 1;
    }

    @Override
    public Iterator getIterator() {
        return new CompanyAEmpRecordsIterator();
    }

    private class CompanyAEmpRecordsIterator implements Iterator {

        int currIndex = -1;

        @Override
        public boolean hasNext() {
            if (currIndex + 1 <= index)
                return true;
            else
                return false;
        }

        @Override
        public Object next() {
            if (currIndex + 1 <= index)
                return companyEmployees[++currIndex];
            else
                return null;
        }

    }

}


You get the point.  And your printing logic will be as simple as  -

    public void pringCompanyEMployeeRecords(CompanyAEmpRecords companyAEmpRecords, CompanyBEmpRecords companyBEmpRecords) {
        
        printRecord(companyAEmpRecords.getIterator());
        printRecord(companyBEmpRecords.getIterator());
    }
    
    private void printRecord(Iterator recordIterator) {
        while(recordIterator.hasNext()) {
            System.out.println(recordIterator.next());
        }
    }


This is just the snippet I have provided. You can download the complete code from my git repository -
NOTE : Instead of defining your own iterator interface you can use java.util.Iterator interface instead.

NOTE :  we have not added remove() method in the Iterator interface. Neither are we handling multi threading scenarios like what happens when the collection gets modified when you are iterating using that iterator. The way this is handled is that when iterator is created we copy the modcount (modification count) and at any point during the iteration this is different than the original count we throw java.util.ConcurrentModificationException.

For sample code you can refer to Iterator provided by ArrayList class in Java -

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }



Class Diagram



Related Links

t> UA-39527780-1 back to top