Search in sources :

Example 1 with PKIStatusInfo

use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project gdmatrix by gdmatrix.

the class CMSUtils method sendData.

private static TimeStampResp sendData(InputStream dataToBeSent, String serviceURI) throws Exception {
    URL url = new URL(serviceURI);
    URLConnection conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    // post request data
    OutputStream os = conn.getOutputStream();
    byte[] buffer = new byte[4096];
    int numRead = dataToBeSent.read(buffer);
    while (numRead > 0) {
        os.write(buffer, 0, numRead);
        numRead = dataToBeSent.read(buffer);
    }
    os.flush();
    // read response
    InputStream response = conn.getInputStream();
    ASN1InputStream asn1Is = new ASN1InputStream(response);
    // TimeStampResp tspResp = new TimeStampResp((ASN1Sequence)asn1Is.readObject());
    Enumeration e = ((ASN1Sequence) asn1Is.readObject()).getObjects();
    PKIStatusInfo pkiStatusInfo = PKIStatusInfo.getInstance(e.nextElement());
    ContentInfo timeStampToken = null;
    if (e.hasMoreElements()) {
        timeStampToken = ContentInfo.getInstance(e.nextElement());
    }
    TimeStampResp tspResp = new TimeStampResp(pkiStatusInfo, timeStampToken);
    return tspResp;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) TimeStampResp(org.bouncycastle.asn1.tsp.TimeStampResp) URL(java.net.URL) URLConnection(java.net.URLConnection)

Example 2 with PKIStatusInfo

use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project ca3sCore by kuehne-trustable-de.

the class CaCmpConnector method readCertResponse.

/**
 * @param responseBytes
 * @param pkiMessageReq
 * @param csr
 * @param config
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws GeneralSecurityException
 */
public de.trustable.ca3s.core.domain.Certificate readCertResponse(final byte[] responseBytes, final PKIMessage pkiMessageReq, final CSR csr, final CAConnectorConfig config) throws IOException, CRMFException, CMPException, GeneralSecurityException {
    final ASN1Primitive derObject = cryptoUtil.getDERObject(responseBytes);
    final PKIMessage pkiMessage = PKIMessage.getInstance(derObject);
    if (pkiMessage == null) {
        throw new GeneralSecurityException("No CMP message could be parsed from received Der object.");
    }
    printPKIMessageInfo(pkiMessage);
    PKIHeader pkiHeaderReq = pkiMessageReq.getHeader();
    PKIHeader pkiHeaderResp = pkiMessage.getHeader();
    if (!pkiHeaderReq.getSenderNonce().equals(pkiHeaderResp.getRecipNonce())) {
        ASN1OctetString asn1Oct = pkiHeaderResp.getRecipNonce();
        if (asn1Oct == null) {
            LOGGER.info("Recip nonce  == null");
        } else {
            LOGGER.info("sender nonce " + java.util.Base64.getEncoder().encodeToString(pkiHeaderReq.getSenderNonce().getOctets()) + " != " + java.util.Base64.getEncoder().encodeToString(asn1Oct.getOctets()));
        }
        throw new GeneralSecurityException("Sender / Recip nonce mismatch");
    }
    if (!pkiHeaderReq.getTransactionID().equals(pkiHeaderResp.getTransactionID())) {
        ASN1OctetString asn1Oct = pkiHeaderResp.getTransactionID();
        if (asn1Oct == null) {
            LOGGER.info("transaction id == null");
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("transaction id " + java.util.Base64.getEncoder().encodeToString(pkiHeaderReq.getTransactionID().getOctets()) + " != " + java.util.Base64.getEncoder().encodeToString(asn1Oct.getOctets()));
            }
        }
        throw new GeneralSecurityException("Sender / Recip Transaction Id mismatch");
    }
    final PKIBody body = pkiMessage.getBody();
    int tagno = body.getType();
    if (tagno == PKIBody.TYPE_ERROR) {
        handleCMPError(body);
    } else if (tagno == PKIBody.TYPE_CERT_REP || tagno == PKIBody.TYPE_INIT_REP) {
        // certificate successfully generated
        CertRepMessage certRepMessage = CertRepMessage.getInstance(body.getContent());
        try {
            // CMPCertificate[] cmpCertArr = certRepMessage.getCaPubs();
            CMPCertificate[] cmpCertArr = pkiMessage.getExtraCerts();
            LOGGER.info("CMP Response body contains " + cmpCertArr.length + " extra certificates");
            for (int i = 0; i < cmpCertArr.length; i++) {
                CMPCertificate cmpCert = cmpCertArr[i];
                LOGGER.info("Added CA '" + cmpCert.getX509v3PKCert().getSubject() + "' from CMP Response body");
                de.trustable.ca3s.core.domain.Certificate certDao = certUtil.createCertificate(cmpCert.getEncoded(), null, null, true);
                certificateRepository.save(certDao);
                LOGGER.debug("Additional CA '" + certDao.getSubject() + "' from CMP Response body");
            }
        } catch (NullPointerException npe) {
        // NOSONAR
        // just ignore
        }
        CertResponse[] respArr = certRepMessage.getResponse();
        if (respArr == null || (respArr.length == 0)) {
            throw new GeneralSecurityException("No CMP response found.");
        }
        LOGGER.info("CMP Response body contains " + respArr.length + " elements");
        for (int i = 0; i < respArr.length; i++) {
            if (respArr[i] == null) {
                throw new GeneralSecurityException("No CMP response returned.");
            }
            BigInteger status = BigInteger.ZERO;
            String statusText = "";
            PKIStatusInfo pkiStatusInfo = respArr[i].getStatus();
            if (pkiStatusInfo != null) {
                PKIFreeText freeText = pkiStatusInfo.getStatusString();
                if (freeText != null) {
                    for (int j = 0; j < freeText.size(); j++) {
                        statusText = freeText.getStringAt(j) + "\n";
                    }
                }
            }
            if ((respArr[i].getCertifiedKeyPair() == null) || (respArr[i].getCertifiedKeyPair().getCertOrEncCert() == null)) {
                csrUtil.setStatus(csr, CsrStatus.REJECTED);
                csrUtil.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_FAILURE_INFO, statusText, true);
                throw new GeneralSecurityException("CMP response contains no certificate, status :" + status + "\n" + statusText);
            }
            CMPCertificate cmpCert = respArr[i].getCertifiedKeyPair().getCertOrEncCert().getCertificate();
            if (cmpCert != null) {
                org.bouncycastle.asn1.x509.Certificate cmpCertificate = cmpCert.getX509v3PKCert();
                if (cmpCertificate != null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("#" + i + ": " + cmpCertificate);
                    }
                    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    /*
						 * version returning just the end entity ...
						 */
                    final Collection<? extends java.security.cert.Certificate> certificateChain = certificateFactory.generateCertificates(new ByteArrayInputStream(cmpCertificate.getEncoded()));
                    X509Certificate[] certArray = certificateChain.toArray(new X509Certificate[0]);
                    X509Certificate cert = certArray[0];
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.info("#" + i + ": " + cert);
                    }
                    de.trustable.ca3s.core.domain.Certificate certDao = certUtil.createCertificate(cert.getEncoded(), csr, null, false);
                    certDao.setRevocationCA(config);
                    certificateRepository.save(certDao);
                    return certDao;
                }
            }
        }
    } else {
        throw new GeneralSecurityException("unexpected PKI body type :" + tagno);
    }
    return null;
}
Also used : PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) GeneralSecurityException(java.security.GeneralSecurityException) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) CertRepMessage(org.bouncycastle.asn1.cmp.CertRepMessage) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) PKIFreeText(org.bouncycastle.asn1.cmp.PKIFreeText) CMPCertificate(org.bouncycastle.asn1.cmp.CMPCertificate) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) Collection(java.util.Collection) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) X509Certificate(java.security.cert.X509Certificate) CMPCertificate(org.bouncycastle.asn1.cmp.CMPCertificate) Certificate(de.trustable.ca3s.core.domain.Certificate)

Example 3 with PKIStatusInfo

use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project xipki by xipki.

the class CmpCaClient method parseEnrollCertResult.

private X509Certificate parseEnrollCertResult(PKIMessage response) throws Exception {
    PKIBody respBody = response.getBody();
    final int bodyType = respBody.getType();
    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
        throw new Exception("Server returned PKIStatus: " + buildText(content.getPKIStatusInfo()));
    } else if (PKIBody.TYPE_CERT_REP != bodyType) {
        throw new Exception(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, PKIBody.TYPE_CERT_REP, PKIBody.TYPE_ERROR));
    }
    CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
    CertResponse[] certResponses = certRep.getResponse();
    if (certResponses.length != 1) {
        throw new Exception("expected 1 CertResponse, but returned " + certResponses.length);
    }
    // We only accept the certificates which are requested.
    CertResponse certResp = certResponses[0];
    PKIStatusInfo statusInfo = certResp.getStatus();
    int status = statusInfo.getStatus().intValue();
    if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
        throw new Exception("Server returned PKIStatus: " + buildText(statusInfo));
    }
    CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
    if (cvk != null) {
        CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
        if (cmpCert != null) {
            X509Certificate cert = SdkUtil.parseCert(cmpCert.getX509v3PKCert().getEncoded());
            if (!verify(caCert, cert)) {
                throw new Exception("The returned certificate is not issued by the given CA");
            }
            return cert;
        }
    }
    throw new Exception("Server did not return any certificate");
}
Also used : CMPCertificate(org.bouncycastle.asn1.cmp.CMPCertificate) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) CertResponse(org.bouncycastle.asn1.cmp.CertResponse) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) CertRepMessage(org.bouncycastle.asn1.cmp.CertRepMessage) ErrorMsgContent(org.bouncycastle.asn1.cmp.ErrorMsgContent) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMPException(org.bouncycastle.cert.cmp.CMPException) InvalidKeyException(java.security.InvalidKeyException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertifiedKeyPair(org.bouncycastle.asn1.cmp.CertifiedKeyPair)

Example 4 with PKIStatusInfo

use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project xipki by xipki.

the class CmpResponder method buildErrorPkiMessage.

// method addProtection
protected PKIMessage buildErrorPkiMessage(ASN1OctetString tid, PKIHeader requestHeader, int failureCode, String statusText) {
    GeneralName respRecipient = requestHeader.getSender();
    PKIHeaderBuilder respHeader = new PKIHeaderBuilder(requestHeader.getPvno().getValue().intValue(), getSender(), respRecipient);
    respHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    if (tid != null) {
        respHeader.setTransactionID(tid);
    }
    ASN1OctetString senderNonce = requestHeader.getSenderNonce();
    if (senderNonce != null) {
        respHeader.setRecipNonce(senderNonce);
    }
    PKIStatusInfo status = generateRejectionStatus(failureCode, statusText);
    ErrorMsgContent error = new ErrorMsgContent(status);
    PKIBody body = new PKIBody(PKIBody.TYPE_ERROR, error);
    return new PKIMessage(respHeader.build(), body);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) PKIHeaderBuilder(org.bouncycastle.asn1.cmp.PKIHeaderBuilder) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ErrorMsgContent(org.bouncycastle.asn1.cmp.ErrorMsgContent) Date(java.util.Date)

Example 5 with PKIStatusInfo

use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project xipki by xipki.

the class X509CaCmpResponderImpl method cmpUnRevokeRemoveCertificates.

// method cmpEnrollCert
private PKIBody cmpUnRevokeRemoveCertificates(PKIMessage request, PKIHeaderBuilder respHeader, CmpControl cmpControl, PKIHeader reqHeader, PKIBody reqBody, CmpRequestorInfo requestor, String msgId, AuditEvent event) {
    Integer requiredPermission = null;
    boolean allRevdetailsOfSameType = true;
    RevReqContent rr = RevReqContent.getInstance(reqBody.getContent());
    RevDetails[] revContent = rr.toRevDetailsArray();
    int len = revContent.length;
    for (int i = 0; i < len; i++) {
        RevDetails revDetails = revContent[i];
        Extensions crlDetails = revDetails.getCrlEntryDetails();
        int reasonCode = CrlReason.UNSPECIFIED.getCode();
        if (crlDetails != null) {
            ASN1ObjectIdentifier extId = Extension.reasonCode;
            ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId);
            if (extValue != null) {
                reasonCode = ASN1Enumerated.getInstance(extValue).getValue().intValue();
            }
        }
        if (reasonCode == XiSecurityConstants.CMP_CRL_REASON_REMOVE) {
            if (requiredPermission == null) {
                event.addEventType(CaAuditConstants.TYPE_CMP_rr_remove);
                requiredPermission = PermissionConstants.REMOVE_CERT;
            } else if (requiredPermission != PermissionConstants.REMOVE_CERT) {
                allRevdetailsOfSameType = false;
                break;
            }
        } else if (reasonCode == CrlReason.REMOVE_FROM_CRL.getCode()) {
            if (requiredPermission == null) {
                event.addEventType(CaAuditConstants.TYPE_CMP_rr_unrevoke);
                requiredPermission = PermissionConstants.UNREVOKE_CERT;
            } else if (requiredPermission != PermissionConstants.UNREVOKE_CERT) {
                allRevdetailsOfSameType = false;
                break;
            }
        } else {
            if (requiredPermission == null) {
                event.addEventType(CaAuditConstants.TYPE_CMP_rr_revoke);
                requiredPermission = PermissionConstants.REVOKE_CERT;
            } else if (requiredPermission != PermissionConstants.REVOKE_CERT) {
                allRevdetailsOfSameType = false;
                break;
            }
        }
    }
    if (!allRevdetailsOfSameType) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText("not all revDetails are of the same type"), new PKIFailureInfo(PKIFailureInfo.badRequest)));
        return new PKIBody(PKIBody.TYPE_ERROR, emc);
    } else {
        try {
            checkPermission(requestor, requiredPermission);
        } catch (InsuffientPermissionException ex) {
            event.setStatus(AuditStatus.FAILED);
            event.addEventData(CaAuditConstants.NAME_message, "NOT_PERMITTED");
            return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.notAuthorized, null);
        }
        return unRevokeRemoveCertificates(request, rr, requiredPermission, cmpControl, msgId);
    }
}
Also used : PKIBody(org.bouncycastle.asn1.cmp.PKIBody) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) InsuffientPermissionException(org.xipki.ca.api.InsuffientPermissionException) Extensions(org.bouncycastle.asn1.x509.Extensions) RevReqContent(org.bouncycastle.asn1.cmp.RevReqContent) PKIFreeText(org.bouncycastle.asn1.cmp.PKIFreeText) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ErrorMsgContent(org.bouncycastle.asn1.cmp.ErrorMsgContent) RevDetails(org.bouncycastle.asn1.cmp.RevDetails) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

PKIStatusInfo (org.bouncycastle.asn1.cmp.PKIStatusInfo)15 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)10 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)8 ErrorMsgContent (org.bouncycastle.asn1.cmp.ErrorMsgContent)8 PKIFreeText (org.bouncycastle.asn1.cmp.PKIFreeText)8 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)7 BigInteger (java.math.BigInteger)6 PKIFailureInfo (org.bouncycastle.asn1.cmp.PKIFailureInfo)6 IOException (java.io.IOException)5 Date (java.util.Date)4 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)4 CMPCertificate (org.bouncycastle.asn1.cmp.CMPCertificate)4 CertRepMessage (org.bouncycastle.asn1.cmp.CertRepMessage)4 CertResponse (org.bouncycastle.asn1.cmp.CertResponse)4 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 CertifiedKeyPair (org.bouncycastle.asn1.cmp.CertifiedKeyPair)3 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)2 PKIStatusInfo (com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo)2 FileInputStream (java.io.FileInputStream)2