OpenSSLX509CertPath.java 8.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Kenny Root's avatar
Kenny Root committed
17
package org.conscrypt;
18 19 20 21 22 23 24 25 26

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
27
import java.util.ArrayList;
28 29 30 31
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
Kenny Root's avatar
Kenny Root committed
32
import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException;
33 34 35 36 37 38 39 40 41 42 43

public class OpenSSLX509CertPath extends CertPath {
    private static final byte[] PKCS7_MARKER = "-----BEGIN PKCS7".getBytes();

    private static final int PUSHBACK_SIZE = 64;

    /**
     * Supported encoding types for CerthPath. Used by the various APIs that
     * encode this into bytes such as {@link #getEncoded()}.
     */
    private enum Encoding {
44
        PKI_PATH("PkiPath"),
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        PKCS7("PKCS7");

        private final String apiName;

        Encoding(String apiName) {
            this.apiName = apiName;
        }

        static Encoding findByApiName(String apiName) throws CertificateEncodingException {
            for (Encoding element : values()) {
                if (element.apiName.equals(apiName)) {
                    return element;
                }
            }

            return null;
        }
    }

    /** Unmodifiable list of encodings for the API. */
    private static final List<String> ALL_ENCODINGS = Collections.unmodifiableList(Arrays
            .asList(new String[] {
67 68
                    Encoding.PKI_PATH.apiName,
                    Encoding.PKCS7.apiName,
69 70
            }));

71
    private static final Encoding DEFAULT_ENCODING = Encoding.PKI_PATH;
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

    private final List<? extends X509Certificate> mCertificates;

    static Iterator<String> getEncodingsIterator() {
        return ALL_ENCODINGS.iterator();
    }

    protected OpenSSLX509CertPath(List<? extends X509Certificate> certificates) {
        super("X.509");

        mCertificates = certificates;
    }

    @Override
    public List<? extends Certificate> getCertificates() {
        return Collections.unmodifiableList(mCertificates);
    }

    private byte[] getEncoded(Encoding encoding) throws CertificateEncodingException {
        final OpenSSLX509Certificate[] certs = new OpenSSLX509Certificate[mCertificates.size()];
        final long[] certRefs = new long[certs.length];

94 95 96 97 98
        for (int i = 0, j = certs.length - 1; j >= 0; i++, j--) {
            final X509Certificate cert = mCertificates.get(i);

            if (cert instanceof OpenSSLX509Certificate) {
                certs[j] = (OpenSSLX509Certificate) cert;
99
            } else {
100
                certs[j] = OpenSSLX509Certificate.fromX509Der(cert.getEncoded());
101
            }
102 103

            certRefs[j] = certs[j].getContext();
104 105
        }

106 107 108 109 110 111 112 113
        switch (encoding) {
            case PKI_PATH:
                return NativeCrypto.ASN1_seq_pack_X509(certRefs);
            case PKCS7:
                return NativeCrypto.i2d_PKCS7(certRefs);
            default:
                throw new CertificateEncodingException("Unknown encoding");
        }
114 115 116 117 118 119 120 121 122 123 124 125 126 127
    }

    @Override
    public byte[] getEncoded() throws CertificateEncodingException {
        return getEncoded(DEFAULT_ENCODING);
    }

    @Override
    public byte[] getEncoded(String encoding) throws CertificateEncodingException {
        Encoding enc = Encoding.findByApiName(encoding);
        if (enc == null) {
            throw new CertificateEncodingException("Invalid encoding: " + encoding);
        }

128
        return getEncoded(enc);
129 130 131 132 133 134 135
    }

    @Override
    public Iterator<String> getEncodings() {
        return getEncodingsIterator();
    }

136 137 138
    private static CertPath fromPkiPathEncoding(InputStream inStream) throws CertificateException {
        OpenSSLBIOInputStream bis = new OpenSSLBIOInputStream(inStream);

139 140 141 142 143
        final boolean markable = inStream.markSupported();
        if (markable) {
            inStream.mark(PUSHBACK_SIZE);
        }

144 145 146 147
        final long[] certRefs;
        try {
            certRefs = NativeCrypto.ASN1_seq_unpack_X509_bio(bis.getBioContext());
        } catch (Exception e) {
148 149 150 151 152 153
            if (markable) {
                try {
                    inStream.reset();
                } catch (IOException ignored) {
                }
            }
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            throw new CertificateException(e);
        } finally {
            NativeCrypto.BIO_free(bis.getBioContext());
        }

        if (certRefs == null) {
            return new OpenSSLX509CertPath(Collections.<X509Certificate> emptyList());
        }

        final List<OpenSSLX509Certificate> certs =
                new ArrayList<OpenSSLX509Certificate>(certRefs.length);
        for (int i = certRefs.length - 1; i >= 0; i--) {
            if (certRefs[i] == 0) {
                continue;
            }
            certs.add(new OpenSSLX509Certificate(certRefs[i]));
        }

        return new OpenSSLX509CertPath(certs);
    }

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    private static CertPath fromPkcs7Encoding(InputStream inStream) throws CertificateException {
        try {
            if (inStream == null || inStream.available() == 0) {
                return new OpenSSLX509CertPath(Collections.<X509Certificate> emptyList());
            }
        } catch (IOException e) {
            throw new CertificateException("Problem reading input stream", e);
        }

        final boolean markable = inStream.markSupported();
        if (markable) {
            inStream.mark(PUSHBACK_SIZE);
        }

        /* Attempt to see if this is a PKCS#7 bag. */
        final PushbackInputStream pbis = new PushbackInputStream(inStream, PUSHBACK_SIZE);
        try {
            final byte[] buffer = new byte[PKCS7_MARKER.length];

            final int len = pbis.read(buffer);
            if (len < 0) {
                /* No need to reset here. The stream was empty or EOF. */
                throw new ParsingException("inStream is empty");
            }
            pbis.unread(buffer, 0, len);

            if (len == PKCS7_MARKER.length && Arrays.equals(PKCS7_MARKER, buffer)) {
                return new OpenSSLX509CertPath(OpenSSLX509Certificate.fromPkcs7PemInputStream(pbis));
            }

            return new OpenSSLX509CertPath(OpenSSLX509Certificate.fromPkcs7DerInputStream(pbis));
        } catch (Exception e) {
            if (markable) {
                try {
                    inStream.reset();
                } catch (IOException ignored) {
                }
            }
            throw new CertificateException(e);
        }
    }

    private static CertPath fromEncoding(InputStream inStream, Encoding encoding)
            throws CertificateException {
        switch (encoding) {
220 221
            case PKI_PATH:
                return fromPkiPathEncoding(inStream);
222 223 224 225 226 227 228 229 230
            case PKCS7:
                return fromPkcs7Encoding(inStream);
            default:
                throw new CertificateEncodingException("Unknown encoding");
        }
    }

    public static CertPath fromEncoding(InputStream inStream, String encoding)
            throws CertificateException {
231
        if (inStream == null) {
232
            throw new CertificateException("inStream == null");
233 234
        }

235 236 237 238 239 240 241 242 243 244 245 246
        Encoding enc = Encoding.findByApiName(encoding);
        if (enc == null) {
            throw new CertificateException("Invalid encoding: " + encoding);
        }

        return fromEncoding(inStream, enc);
    }

    public static CertPath fromEncoding(InputStream inStream) throws CertificateException {
        return fromEncoding(inStream, DEFAULT_ENCODING);
    }
}