Home | History | Annotate | Download | only in security
      1 /*
      2  * Copyright (C) 2009 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 android.security;
     18 
     19 import android.content.ActivityNotFoundException;
     20 import android.content.Context;
     21 import android.content.Intent;
     22 import android.util.Log;
     23 import com.android.org.bouncycastle.util.io.pem.PemObject;
     24 import com.android.org.bouncycastle.util.io.pem.PemReader;
     25 import com.android.org.bouncycastle.util.io.pem.PemWriter;
     26 import java.io.ByteArrayInputStream;
     27 import java.io.ByteArrayOutputStream;
     28 import java.io.IOException;
     29 import java.io.InputStreamReader;
     30 import java.io.ObjectOutputStream;
     31 import java.io.OutputStreamWriter;
     32 import java.io.Reader;
     33 import java.io.Writer;
     34 import java.nio.charset.StandardCharsets;
     35 import java.security.KeyPair;
     36 import java.security.cert.Certificate;
     37 import java.security.cert.CertificateEncodingException;
     38 import java.security.cert.CertificateException;
     39 import java.security.cert.CertificateFactory;
     40 import java.security.cert.X509Certificate;
     41 import java.util.ArrayList;
     42 import java.util.List;
     43 
     44 /**
     45  * {@hide}
     46  */
     47 public class Credentials {
     48     private static final String LOGTAG = "Credentials";
     49 
     50     public static final String INSTALL_ACTION = "android.credentials.INSTALL";
     51 
     52     public static final String INSTALL_AS_USER_ACTION = "android.credentials.INSTALL_AS_USER";
     53 
     54     public static final String UNLOCK_ACTION = "com.android.credentials.UNLOCK";
     55 
     56     /** Key prefix for CA certificates. */
     57     public static final String CA_CERTIFICATE = "CACERT_";
     58 
     59     /** Key prefix for user certificates. */
     60     public static final String USER_CERTIFICATE = "USRCERT_";
     61 
     62     /** Key prefix for user private keys. */
     63     public static final String USER_PRIVATE_KEY = "USRPKEY_";
     64 
     65     /** Key prefix for VPN. */
     66     public static final String VPN = "VPN_";
     67 
     68     /** Key prefix for WIFI. */
     69     public static final String WIFI = "WIFI_";
     70 
     71     /** Key containing suffix of lockdown VPN profile. */
     72     public static final String LOCKDOWN_VPN = "LOCKDOWN_VPN";
     73 
     74     /** Data type for public keys. */
     75     public static final String EXTRA_PUBLIC_KEY = "KEY";
     76 
     77     /** Data type for private keys. */
     78     public static final String EXTRA_PRIVATE_KEY = "PKEY";
     79 
     80     // historically used by Android
     81     public static final String EXTENSION_CRT = ".crt";
     82     public static final String EXTENSION_P12 = ".p12";
     83     // commonly used on Windows
     84     public static final String EXTENSION_CER = ".cer";
     85     public static final String EXTENSION_PFX = ".pfx";
     86 
     87     /**
     88      * Intent extra: install the certificate bundle as this UID instead of
     89      * system.
     90      */
     91     public static final String EXTRA_INSTALL_AS_UID = "install_as_uid";
     92 
     93     /**
     94      * Intent extra: name for the user's private key.
     95      */
     96     public static final String EXTRA_USER_PRIVATE_KEY_NAME = "user_private_key_name";
     97 
     98     /**
     99      * Intent extra: data for the user's private key in PEM-encoded PKCS#8.
    100      */
    101     public static final String EXTRA_USER_PRIVATE_KEY_DATA = "user_private_key_data";
    102 
    103     /**
    104      * Intent extra: name for the user's certificate.
    105      */
    106     public static final String EXTRA_USER_CERTIFICATE_NAME = "user_certificate_name";
    107 
    108     /**
    109      * Intent extra: data for the user's certificate in PEM-encoded X.509.
    110      */
    111     public static final String EXTRA_USER_CERTIFICATE_DATA = "user_certificate_data";
    112 
    113     /**
    114      * Intent extra: name for CA certificate chain
    115      */
    116     public static final String EXTRA_CA_CERTIFICATES_NAME = "ca_certificates_name";
    117 
    118     /**
    119      * Intent extra: data for CA certificate chain in PEM-encoded X.509.
    120      */
    121     public static final String EXTRA_CA_CERTIFICATES_DATA = "ca_certificates_data";
    122 
    123     /**
    124      * Convert objects to a PEM format which is used for
    125      * CA_CERTIFICATE and USER_CERTIFICATE entries.
    126      */
    127     public static byte[] convertToPem(Certificate... objects)
    128             throws IOException, CertificateEncodingException {
    129         ByteArrayOutputStream bao = new ByteArrayOutputStream();
    130         Writer writer = new OutputStreamWriter(bao, StandardCharsets.US_ASCII);
    131         PemWriter pw = new PemWriter(writer);
    132         for (Certificate o : objects) {
    133             pw.writeObject(new PemObject("CERTIFICATE", o.getEncoded()));
    134         }
    135         pw.close();
    136         return bao.toByteArray();
    137     }
    138     /**
    139      * Convert objects from PEM format, which is used for
    140      * CA_CERTIFICATE and USER_CERTIFICATE entries.
    141      */
    142     public static List<X509Certificate> convertFromPem(byte[] bytes)
    143             throws IOException, CertificateException {
    144         ByteArrayInputStream bai = new ByteArrayInputStream(bytes);
    145         Reader reader = new InputStreamReader(bai, StandardCharsets.US_ASCII);
    146         PemReader pr = new PemReader(reader);
    147 
    148         CertificateFactory cf = CertificateFactory.getInstance("X509");
    149 
    150         List<X509Certificate> result = new ArrayList<X509Certificate>();
    151         PemObject o;
    152         while ((o = pr.readPemObject()) != null) {
    153             if (o.getType().equals("CERTIFICATE")) {
    154                 Certificate c = cf.generateCertificate(new ByteArrayInputStream(o.getContent()));
    155                 result.add((X509Certificate) c);
    156             } else {
    157                 throw new IllegalArgumentException("Unknown type " + o.getType());
    158             }
    159         }
    160         pr.close();
    161         return result;
    162     }
    163 
    164     private static Credentials singleton;
    165 
    166     public static Credentials getInstance() {
    167         if (singleton == null) {
    168             singleton = new Credentials();
    169         }
    170         return singleton;
    171     }
    172 
    173     public void unlock(Context context) {
    174         try {
    175             Intent intent = new Intent(UNLOCK_ACTION);
    176             context.startActivity(intent);
    177         } catch (ActivityNotFoundException e) {
    178             Log.w(LOGTAG, e.toString());
    179         }
    180     }
    181 
    182     public void install(Context context) {
    183         try {
    184             Intent intent = KeyChain.createInstallIntent();
    185             context.startActivity(intent);
    186         } catch (ActivityNotFoundException e) {
    187             Log.w(LOGTAG, e.toString());
    188         }
    189     }
    190 
    191     public void install(Context context, KeyPair pair) {
    192         try {
    193             Intent intent = KeyChain.createInstallIntent();
    194             intent.putExtra(EXTRA_PRIVATE_KEY, pair.getPrivate().getEncoded());
    195             intent.putExtra(EXTRA_PUBLIC_KEY, pair.getPublic().getEncoded());
    196             context.startActivity(intent);
    197         } catch (ActivityNotFoundException e) {
    198             Log.w(LOGTAG, e.toString());
    199         }
    200     }
    201 
    202     public void install(Context context, String type, byte[] value) {
    203         try {
    204             Intent intent = KeyChain.createInstallIntent();
    205             intent.putExtra(type, value);
    206             context.startActivity(intent);
    207         } catch (ActivityNotFoundException e) {
    208             Log.w(LOGTAG, e.toString());
    209         }
    210     }
    211 
    212     /**
    213      * Delete all types (private key, certificate, CA certificate) for a
    214      * particular {@code alias}. All three can exist for any given alias.
    215      * Returns {@code true} if there was at least one of those types.
    216      */
    217     static boolean deleteAllTypesForAlias(KeyStore keystore, String alias) {
    218         /*
    219          * Make sure every type is deleted. There can be all three types, so
    220          * don't use a conditional here.
    221          */
    222         return keystore.delKey(Credentials.USER_PRIVATE_KEY + alias)
    223                 | deleteCertificateTypesForAlias(keystore, alias);
    224     }
    225 
    226     /**
    227      * Delete all types (private key, certificate, CA certificate) for a
    228      * particular {@code alias}. All three can exist for any given alias.
    229      * Returns {@code true} if there was at least one of those types.
    230      */
    231     static boolean deleteCertificateTypesForAlias(KeyStore keystore, String alias) {
    232         /*
    233          * Make sure every certificate type is deleted. There can be two types,
    234          * so don't use a conditional here.
    235          */
    236         return keystore.delete(Credentials.USER_CERTIFICATE + alias)
    237                 | keystore.delete(Credentials.CA_CERTIFICATE + alias);
    238     }
    239 }
    240