crypto: Read certificate chain

If the keychain holds additional certificates other than the end
certificate, read them into the certificate chain.

Bug: 34688653
Test: Enterprise regression tests
Change-Id: I86857ccf25b37b80f9da20f4d5cf3d81e6025d6f
diff --git a/src/crypto/tls_openssl.c b/src/crypto/tls_openssl.c
index a7d4880..1abc282 100644
--- a/src/crypto/tls_openssl.c
+++ b/src/crypto/tls_openssl.c
@@ -2363,15 +2363,26 @@
 		BIO *bio = BIO_from_keystore(&client_cert[11]);
 		X509 *x509 = NULL;
 		int ret = -1;
-		if (bio) {
+		if (bio)
 			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
-			BIO_free(bio);
-		}
+
 		if (x509) {
 			if (SSL_use_certificate(conn->ssl, x509) == 1)
 				ret = 0;
 			X509_free(x509);
 		}
+
+		/* Read additional certificates into the chain. */
+		while (bio) {
+			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
+			if (x509) {
+				/* Takes ownership of x509 */
+				SSL_add0_chain_cert(conn->ssl, x509);
+			} else {
+				BIO_free(bio);
+				bio = NULL;
+			}
+		}
 		return ret;
 	}
 #endif /* ANDROID */