Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do public key pinning in Flutter?

I want to the pin the public key of my server so that any request made to the server has to have that public key (this is to prevent proxies like Charles sniffing the data).

I had done something similar in Android with Volley.

How can I do the same with Flutter?

like image 859
Harsh Bhikadia Avatar asked Jan 26 '23 17:01

Harsh Bhikadia


2 Answers

Create your client with a SecurityContext with no trusted roots to force the bad certificate callback, even for a good certificate.

SecurityContext(withTrustedRoots: false);

In the bad certificate callback, parse the DER encoded certificate using the asn1lib package. For example:

ASN1Parser p = ASN1Parser(der);
ASN1Sequence signedCert = p.nextObject() as ASN1Sequence;
ASN1Sequence cert = signedCert.elements[0] as ASN1Sequence;
ASN1Sequence pubKeyElement = cert.elements[6] as ASN1Sequence;

ASN1BitString pubKeyBits = pubKeyElement.elements[1] as ASN1BitString;

List<int> encodedPubKey = pubKeyBits.stringValue;
// could stop here and compare the encoded key parts, or...

// parse them into their modulus/exponent parts, and test those
// (assumes RSA public key)
ASN1Parser rsaParser = ASN1Parser(encodedPubKey);
ASN1Sequence keySeq = rsaParser.nextObject() as ASN1Sequence;
ASN1Integer modulus = keySeq.elements[0] as ASN1Integer;
ASN1Integer exponent = keySeq.elements[1] as ASN1Integer;

print(modulus.valueAsBigInteger);
print(exponent);
like image 167
Richard Heap Avatar answered Jan 29 '23 08:01

Richard Heap


Key rotation reduces risk. When an attacker obtains an old server hard drive or backup file and gets an old server private key from it, they cannot impersonate the current server if the key has been rotated. Therefore always generate a new key when updating certificates. Configure the client to trust the old key and the new key. Wait for your users to update to the new version of the client. Then deploy the new key to your servers. Then you can remove the old key from the client.

Server key pinning is only needed if you're not rotating keys. That's bad security practice.

You should do certificate pinning with rotation. I have added example code in How to do SSL pinning via self generated signed certificates in flutter?

like image 35
M. Leonhard Avatar answered Jan 29 '23 08:01

M. Leonhard