Search in sources :

Example 96 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project xipki by xipki.

the class OcspServerImpl method answer.

@Override
public OcspRespWithCacheInfo answer(Responder responder2, byte[] request, boolean viaGet) {
    ResponderImpl responder = (ResponderImpl) responder2;
    RequestOption reqOpt = responder.getRequestOption();
    int version;
    try {
        version = OcspRequest.readRequestVersion(request);
    } catch (EncodingException ex) {
        String message = "could not extract version from request";
        LOG.warn(message);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
    }
    if (!reqOpt.isVersionAllowed(version)) {
        String message = "invalid request version " + version;
        LOG.warn(message);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
    }
    ResponderSigner signer = responder.getSigner();
    ResponseOption repOpt = responder.getResponseOption();
    try {
        Object reqOrRrrorResp = checkSignature(request, reqOpt);
        if (reqOrRrrorResp instanceof OcspRespWithCacheInfo) {
            return (OcspRespWithCacheInfo) reqOrRrrorResp;
        }
        OcspRequest req = (OcspRequest) reqOrRrrorResp;
        List<CertID> requestList = req.getRequestList();
        int requestsSize = requestList.size();
        if (requestsSize > reqOpt.getMaxRequestListCount()) {
            String message = requestsSize + " entries in RequestList, but maximal " + reqOpt.getMaxRequestListCount() + " is allowed";
            LOG.warn(message);
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
        }
        OcspRespControl repControl = new OcspRespControl();
        repControl.canCacheInfo = true;
        List<ExtendedExtension> reqExtensions = req.getExtensions();
        List<Extension> respExtensions = new LinkedList<>();
        ExtendedExtension nonceExtn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_NONCE);
        if (nonceExtn != null) {
            if (reqOpt.getNonceOccurrence() == TripleState.FORBIDDEN) {
                LOG.warn("nonce forbidden, but is present in the request");
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
            int len = nonceExtn.getExtnValueLength();
            int min = reqOpt.getNonceMinLen();
            int max = reqOpt.getNonceMaxLen();
            if (len < min || len > max) {
                LOG.warn("length of nonce {} not within [{},{}]", len, min, max);
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
            repControl.canCacheInfo = false;
            respExtensions.add(nonceExtn);
        } else {
            if (reqOpt.getNonceOccurrence() == TripleState.REQUIRED) {
                LOG.warn("nonce required, but is not present in the request");
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
        }
        ConcurrentContentSigner concurrentSigner = null;
        if (responder.getResponderOption().getMode() != OcspMode.RFC2560) {
            ExtendedExtension extn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_PREFSIGALGS);
            if (extn != null) {
                ASN1InputStream asn1Stream = new ASN1InputStream(extn.getExtnValueStream());
                List<AlgorithmIdentifier> prefSigAlgs;
                try {
                    ASN1Sequence seq = ASN1Sequence.getInstance(asn1Stream.readObject());
                    final int size = seq.size();
                    prefSigAlgs = new ArrayList<>(size);
                    for (int i = 0; i < size; i++) {
                        prefSigAlgs.add(AlgorithmIdentifier.getInstance(seq.getObjectAt(i)));
                    }
                } finally {
                    asn1Stream.close();
                }
                concurrentSigner = signer.getSignerForPreferredSigAlgs(prefSigAlgs);
            }
        }
        if (!reqExtensions.isEmpty()) {
            boolean flag = false;
            for (ExtendedExtension m : reqExtensions) {
                if (m.isCritical()) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                if (LOG.isWarnEnabled()) {
                    List<OID> oids = new LinkedList<>();
                    for (ExtendedExtension m : reqExtensions) {
                        if (m.isCritical()) {
                            oids.add(m.getExtnType());
                        }
                    }
                    LOG.warn("could not process critial request extensions: {}", oids);
                }
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
        }
        if (concurrentSigner == null) {
            concurrentSigner = signer.getFirstSigner();
        }
        AlgorithmCode cacheDbSigAlgCode = null;
        BigInteger cacheDbSerialNumber = null;
        Integer cacheDbIssuerId = null;
        boolean canCacheDb = (requestsSize == 1) && (responseCacher != null) && (nonceExtn == null) && responseCacher.isOnService();
        if (canCacheDb) {
            // try to find the cached response
            CertID certId = requestList.get(0);
            HashAlgo reqHashAlgo = certId.getIssuer().hashAlgorithm();
            if (!reqOpt.allows(reqHashAlgo)) {
                LOG.warn("CertID.hashAlgorithm {} not allowed", reqHashAlgo != null ? reqHashAlgo : certId.getIssuer().hashAlgorithmOID());
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
            cacheDbSigAlgCode = concurrentSigner.getAlgorithmCode();
            cacheDbIssuerId = responseCacher.getIssuerId(certId.getIssuer());
            cacheDbSerialNumber = certId.getSerialNumber();
            if (cacheDbIssuerId != null) {
                OcspRespWithCacheInfo cachedResp = responseCacher.getOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, cacheDbSigAlgCode);
                if (cachedResp != null) {
                    return cachedResp;
                }
            } else if (master) {
                // store the issuer certificate in cache database.
                X509Certificate issuerCert = null;
                for (OcspStore store : responder.getStores()) {
                    issuerCert = store.getIssuerCert(certId.getIssuer());
                    if (issuerCert != null) {
                        break;
                    }
                }
                if (issuerCert != null) {
                    cacheDbIssuerId = responseCacher.storeIssuer(issuerCert);
                }
            }
            if (cacheDbIssuerId == null) {
                canCacheDb = false;
            }
        }
        ResponderID responderId = signer.getResponderId(repOpt.isResponderIdByName());
        OCSPRespBuilder builder = new OCSPRespBuilder(responderId);
        for (int i = 0; i < requestsSize; i++) {
            OcspRespWithCacheInfo failureOcspResp = processCertReq(requestList.get(i), builder, responder, reqOpt, repOpt, repControl);
            if (failureOcspResp != null) {
                return failureOcspResp;
            }
        }
        if (repControl.includeExtendedRevokeExtension) {
            respExtensions.add(extension_pkix_ocsp_extendedRevoke);
        }
        if (!respExtensions.isEmpty()) {
            Extensions extns = new Extensions(respExtensions);
            builder.setResponseExtensions(extns);
        }
        TaggedCertSequence certsInResp;
        EmbedCertsMode certsMode = repOpt.getEmbedCertsMode();
        if (certsMode == EmbedCertsMode.SIGNER) {
            certsInResp = signer.getSequenceOfCert();
        } else if (certsMode == EmbedCertsMode.NONE) {
            certsInResp = null;
        } else {
            // certsMode == EmbedCertsMode.SIGNER_AND_CA
            certsInResp = signer.getSequenceOfCertChain();
        }
        byte[] encodeOcspResponse;
        try {
            encodeOcspResponse = builder.buildOCSPResponse(concurrentSigner, certsInResp, new Date());
        } catch (NoIdleSignerException ex) {
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.tryLater);
        } catch (OCSPException ex) {
            LogUtil.error(LOG, ex, "answer() basicOcspBuilder.build");
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
        }
        // cache response in database
        if (canCacheDb && repControl.canCacheInfo) {
            // Don't cache the response with status UNKNOWN, since this may result in DDoS
            // of storage
            responseCacher.storeOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, repControl.cacheThisUpdate, repControl.cacheNextUpdate, cacheDbSigAlgCode, encodeOcspResponse);
        }
        if (viaGet && repControl.canCacheInfo) {
            ResponseCacheInfo cacheInfo = new ResponseCacheInfo(repControl.cacheThisUpdate);
            if (repControl.cacheNextUpdate != Long.MAX_VALUE) {
                cacheInfo.setNextUpdate(repControl.cacheNextUpdate);
            }
            return new OcspRespWithCacheInfo(encodeOcspResponse, cacheInfo);
        } else {
            return new OcspRespWithCacheInfo(encodeOcspResponse, null);
        }
    } catch (Throwable th) {
        LogUtil.error(LOG, th);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
    }
}
Also used : EncodingException(org.xipki.ocsp.server.impl.type.EncodingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertID(org.xipki.ocsp.server.impl.type.CertID) ExtendedExtension(org.xipki.ocsp.server.impl.type.ExtendedExtension) HashAlgo(org.xipki.security.HashAlgo) ResponderID(org.xipki.ocsp.server.impl.type.ResponderID) Extensions(org.xipki.ocsp.server.impl.type.Extensions) AlgorithmCode(org.xipki.security.AlgorithmCode) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OcspStore(org.xipki.ocsp.api.OcspStore) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspRespWithCacheInfo(org.xipki.ocsp.api.OcspRespWithCacheInfo) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) OID(org.xipki.ocsp.server.impl.type.OID) TaggedCertSequence(org.xipki.ocsp.server.impl.type.TaggedCertSequence) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) Extension(org.xipki.ocsp.server.impl.type.Extension) WritableOnlyExtension(org.xipki.ocsp.server.impl.type.WritableOnlyExtension) ExtendedExtension(org.xipki.ocsp.server.impl.type.ExtendedExtension) BigInteger(java.math.BigInteger) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) EmbedCertsMode(org.xipki.ocsp.server.impl.jaxb.EmbedCertsMode) ResponseCacheInfo(org.xipki.ocsp.api.OcspRespWithCacheInfo.ResponseCacheInfo) BigInteger(java.math.BigInteger) OcspRequest(org.xipki.ocsp.server.impl.type.OcspRequest)

Example 97 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project certmgr by hdecarne.

the class DERCertReaderWriter method readBinary.

@Override
@Nullable
public CertObjectStore readBinary(IOResource<InputStream> in, PasswordCallback password) throws IOException {
    LOG.debug("Trying to read DER objects from: ''{0}''...", in);
    CertObjectStore certObjects = null;
    try (ASN1InputStream derStream = new ASN1InputStream(in.io())) {
        ASN1Primitive derObject;
        while ((derObject = derStream.readObject()) != null) {
            X509Certificate crt = tryDecodeCRT(derObject);
            if (crt != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addCRT(crt);
                continue;
            }
            KeyPair key = tryDecodeKey(derObject, in.resource(), password);
            if (key != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addKey(key);
                continue;
            }
            PKCS10CertificateRequest csr = tryDecodeCSR(derObject);
            if (csr != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addCSR(csr);
                continue;
            }
            X509CRL crl = tryDecodeCRL(derObject);
            if (crl != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addCRL(crl);
                continue;
            }
            LOG.warning(CertIOI18N.STR_DER_UNKNOWN_OBJECT, derObject.getClass().getName());
        }
    } catch (ClassCastException e) {
        // the file is not a DER stream
        throw new CertProviderException(e);
    }
    return certObjects;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPair(java.security.KeyPair) X509CRL(java.security.cert.X509CRL) PKCS10CertificateRequest(de.carne.certmgr.certs.x509.PKCS10CertificateRequest) CertObjectStore(de.carne.certmgr.certs.CertObjectStore) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CertProviderException(de.carne.certmgr.certs.CertProviderException) X509Certificate(java.security.cert.X509Certificate) Nullable(de.carne.check.Nullable)

Example 98 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project android_packages_apps_Settings by omnirom.

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getAlgorithmId().getAlgorithm().getId();
        String algName = new AlgorithmId(new ObjectIdentifier(algOid)).getName();
        return KeyChain.isBoundKeyAlgorithm(algName);
    } catch (IOException e) {
        Log.e(TAG, "Failed to parse key data");
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AlgorithmId(sun.security.x509.AlgorithmId) IOException(java.io.IOException) PrivateKeyInfo(com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 99 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project android_packages_apps_Settings by omnirom.

the class CertInstallerHelper method isCa.

private boolean isCa(X509Certificate cert) {
    try {
        byte[] asn1EncodedBytes = cert.getExtensionValue("2.5.29.19");
        if (asn1EncodedBytes == null) {
            return false;
        }
        DEROctetString derOctetString = (DEROctetString) new ASN1InputStream(asn1EncodedBytes).readObject();
        byte[] octets = derOctetString.getOctets();
        ASN1Sequence sequence = (ASN1Sequence) new ASN1InputStream(octets).readObject();
        return BasicConstraints.getInstance(sequence).isCA();
    } catch (IOException e) {
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(com.android.org.bouncycastle.asn1.ASN1Sequence) IOException(java.io.IOException) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString)

Example 100 with ASN1InputStream

use of org.gudy.bouncycastle.asn1.ASN1InputStream in project signer by demoiselle.

the class OIDGeneric method getInstance.

/**
 * Instance for OIDGeneric.
 *
 * @param data
 *            Set of bytes with the contents of the certificate.
 * @return Object GenericOID
 * @throws IOException exception of input/output
 * @throws Exception general exception
 */
public static OIDGeneric getInstance(byte[] data) throws IOException, Exception {
    is = new ASN1InputStream(data);
    DLSequence sequence = (DLSequence) is.readObject();
    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) sequence.getObjectAt(0);
    DERTaggedObject taggedObject = (DERTaggedObject) sequence.getObjectAt(1);
    DERTaggedObject taggedObject2 = (DERTaggedObject) taggedObject.getObject();
    DEROctetString octet = null;
    DERPrintableString print = null;
    DERUTF8String utf8 = null;
    DERIA5String ia5 = null;
    try {
        octet = (DEROctetString) taggedObject2.getObject();
    } catch (Exception e) {
        try {
            print = (DERPrintableString) taggedObject2.getObject();
        } catch (Exception e1) {
            try {
                utf8 = (DERUTF8String) taggedObject2.getObject();
            } catch (Exception e2) {
                ia5 = (DERIA5String) taggedObject2.getObject();
            }
        }
    }
    String className = getPackageName() + oid.getId().replaceAll("[.]", "_");
    OIDGeneric oidGenerico;
    try {
        oidGenerico = (OIDGeneric) Class.forName(className).newInstance();
    } catch (InstantiationException e) {
        throw new Exception(coreMessagesBundle.getString("error.class.instance", className), e);
    } catch (IllegalAccessException e) {
        throw new Exception(coreMessagesBundle.getString("error.class.illegal.access", className), e);
    } catch (ClassNotFoundException e) {
        oidGenerico = new OIDGeneric();
    }
    oidGenerico.oid = oid.getId();
    if (octet != null) {
        oidGenerico.data = new String(octet.getOctets());
    } else {
        if (print != null) {
            oidGenerico.data = print.getString();
        } else {
            if (utf8 != null) {
                oidGenerico.data = utf8.getString();
            } else {
                oidGenerico.data = ia5.getString();
            }
        }
    }
    oidGenerico.initialize();
    return oidGenerico;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) DERIA5String(org.bouncycastle.asn1.DERIA5String) DLSequence(org.bouncycastle.asn1.DLSequence) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)99 IOException (java.io.IOException)81 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)34 ByteArrayInputStream (java.io.ByteArrayInputStream)28 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)22 BigInteger (java.math.BigInteger)20 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)19 CertificateException (java.security.cert.CertificateException)19 X509Certificate (java.security.cert.X509Certificate)19 DEROctetString (org.bouncycastle.asn1.DEROctetString)19 CertificateParsingException (java.security.cert.CertificateParsingException)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17 Enumeration (java.util.Enumeration)17 CertificateEncodingException (java.security.cert.CertificateEncodingException)16 InvalidKeyException (java.security.InvalidKeyException)14 CRLException (java.security.cert.CRLException)14 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)14 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)12 NoSuchProviderException (java.security.NoSuchProviderException)11 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)11