1 /** 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.rkpdapp.utils; 18 19 import android.util.Base64; 20 import android.util.Log; 21 22 import com.android.rkpdapp.RkpdException; 23 24 import java.io.ByteArrayInputStream; 25 import java.math.BigInteger; 26 import java.security.InvalidAlgorithmParameterException; 27 import java.security.InvalidKeyException; 28 import java.security.NoSuchAlgorithmException; 29 import java.security.NoSuchProviderException; 30 import java.security.PublicKey; 31 import java.security.SignatureException; 32 import java.security.cert.CertPathValidator; 33 import java.security.cert.CertPathValidatorException; 34 import java.security.cert.Certificate; 35 import java.security.cert.CertificateException; 36 import java.security.cert.CertificateFactory; 37 import java.security.cert.PKIXParameters; 38 import java.security.cert.TrustAnchor; 39 import java.security.cert.X509Certificate; 40 import java.security.interfaces.ECPublicKey; 41 import java.util.ArrayList; 42 import java.util.Arrays; 43 import java.util.Set; 44 45 /** 46 * Provides convenience methods for parsing certificates and extracting information. 47 */ 48 public class X509Utils { 49 50 private static final String TAG = "RkpdX509Utils"; 51 52 /** 53 * Takes a byte array composed of DER encoded certificates and returns the X.509 certificates 54 * contained within as an X509Certificate array. 55 */ formatX509Certs(byte[] certStream)56 public static X509Certificate[] formatX509Certs(byte[] certStream) throws RkpdException { 57 try { 58 CertificateFactory fact = CertificateFactory.getInstance("X.509"); 59 ByteArrayInputStream in = new ByteArrayInputStream(certStream); 60 ArrayList<Certificate> certs = new ArrayList<>(fact.generateCertificates(in)); 61 X509Certificate[] certChain = certs.toArray(new X509Certificate[0]); 62 if (isCertChainValid(certChain)) { 63 return certChain; 64 } else { 65 throw new RkpdException(RkpdException.ErrorCode.INTERNAL_ERROR, 66 "Could not validate certificate chain."); 67 } 68 } catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException 69 | InvalidAlgorithmParameterException e) { 70 Log.e(TAG, "Unable to parse certificate chain." 71 + Base64.encodeToString(certStream, Base64.DEFAULT), e); 72 throw new RkpdException(RkpdException.ErrorCode.INTERNAL_ERROR, 73 "Failed to interpret DER encoded certificate chain", e); 74 } 75 } 76 77 /** 78 * Extracts an ECDSA-P256 key from a certificate and formats it so that it can be used to match 79 * the certificate chain to the proper key when passed into the keystore database. 80 */ getAndFormatRawPublicKey(X509Certificate cert)81 public static byte[] getAndFormatRawPublicKey(X509Certificate cert) { 82 PublicKey pubKey = cert.getPublicKey(); 83 if (!(pubKey instanceof ECPublicKey)) { 84 Log.e(TAG, "Certificate public key is not an instance of ECPublicKey"); 85 return null; 86 } 87 ECPublicKey key = (ECPublicKey) cert.getPublicKey(); 88 // Remote key provisioning internally supports the default, uncompressed public key 89 // format for ECDSA. This defines the format as (s | x | y), where s is the byte 90 // indicating if the key is compressed or not, and x and y make up the EC point. 91 // However, the key as stored in a COSE_Key object is just the two points. As such, 92 // the raw public key is stored in the database as (x | y), so the compression byte 93 // should be dropped here. Leading 0's must be preserved. 94 // 95 // s: 1 byte, x: 32 bytes, y: 32 bytes 96 BigInteger xCoord = key.getW().getAffineX(); 97 BigInteger yCoord = key.getW().getAffineY(); 98 byte[] formattedKey = new byte[64]; 99 byte[] xBytes = xCoord.toByteArray(); 100 // BigInteger returns the value as two's complement big endian byte encoding. This means 101 // that a positive, 32-byte value with a leading 1 bit will be converted to a byte array of 102 // length 33 in order to include a leading 0 bit. 103 if (xBytes.length == 33) { 104 System.arraycopy(xBytes, 1 /* offset */, formattedKey, 0 /* offset */, 32); 105 } else { 106 System.arraycopy(xBytes, 0 /* offset */, 107 formattedKey, 32 - xBytes.length, xBytes.length); 108 } 109 byte[] yBytes = yCoord.toByteArray(); 110 if (yBytes.length == 33) { 111 System.arraycopy(yBytes, 1 /* offset */, formattedKey, 32 /* offset */, 32); 112 } else { 113 System.arraycopy(yBytes, 0 /* offset */, 114 formattedKey, 64 - yBytes.length, yBytes.length); 115 } 116 return formattedKey; 117 } 118 119 /** 120 * Validates the X509 certificate chain and returns appropriate boolean result. 121 */ isCertChainValid(X509Certificate[] certChain)122 public static boolean isCertChainValid(X509Certificate[] certChain) 123 throws NoSuchAlgorithmException, NoSuchProviderException, 124 InvalidAlgorithmParameterException { 125 X509Certificate rootCert = certChain[certChain.length - 1]; 126 return isSelfSignedCertificate(rootCert) && verifyCertChain(rootCert, certChain); 127 } 128 verifyCertChain(X509Certificate rootCert, X509Certificate[] certChain)129 private static boolean verifyCertChain(X509Certificate rootCert, X509Certificate[] certChain) 130 throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { 131 try { 132 // Only add the self-signed root certificate as trust anchor. 133 // All the other certificates in the chain should be signed by the previous cert's key. 134 Set<TrustAnchor> trustedAnchors = Set.of(new TrustAnchor(rootCert, null)); 135 136 CertificateFactory fact = CertificateFactory.getInstance("X.509"); 137 CertPathValidator validator = CertPathValidator.getInstance("PKIX"); 138 PKIXParameters parameters = new PKIXParameters(trustedAnchors); 139 parameters.setRevocationEnabled(false); 140 validator.validate(fact.generateCertPath(Arrays.asList(certChain)), parameters); 141 return true; 142 } catch (CertificateException | CertPathValidatorException e) { 143 Log.e(TAG, "certificate chain validation failed.", e); 144 return false; 145 } 146 } 147 148 /** 149 * Verifies whether an X509Certificate is a self-signed certificate. 150 */ isSelfSignedCertificate(X509Certificate certificate)151 public static boolean isSelfSignedCertificate(X509Certificate certificate) 152 throws NoSuchAlgorithmException, NoSuchProviderException { 153 try { 154 certificate.verify(certificate.getPublicKey()); 155 return true; 156 } catch (SignatureException | InvalidKeyException | CertificateException e) { 157 Log.e(TAG, "Error verifying self signed certificate", e); 158 return false; 159 } 160 } 161 } 162