Search in sources :

Example 16 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project xipki by xipki.

the class BaseCmpResponder method verifyPop.

protected boolean verifyPop(CertificateRequestMessage certRequest, SubjectPublicKeyInfo spki, boolean allowRaPop) {
    int popType = certRequest.getProofOfPossessionType();
    if (popType == CertificateRequestMessage.popRaVerified && allowRaPop) {
        return true;
    }
    if (popType != CertificateRequestMessage.popSigningKey) {
        LOG.error("unsupported POP type: " + popType);
        return false;
    }
    // check the POP signature algorithm
    ProofOfPossession pop = certRequest.toASN1Structure().getPop();
    POPOSigningKey popSign = POPOSigningKey.getInstance(pop.getObject());
    SignAlgo popAlg;
    try {
        popAlg = SignAlgo.getInstance(popSign.getAlgorithmIdentifier());
    } catch (NoSuchAlgorithmException ex) {
        LogUtil.error(LOG, ex, "Cannot parse POP signature algorithm");
        return false;
    }
    AlgorithmValidator algoValidator = getCa().getPopAlgoValidator();
    if (!algoValidator.isAlgorithmPermitted(popAlg)) {
        LOG.error("POP signature algorithm {} not permitted", popAlg.getJceName());
        return false;
    }
    try {
        PublicKey publicKey = securityFactory.generatePublicKey(spki);
        PopControl popControl = getCa().getCaInfo().getPopControl();
        DHSigStaticKeyCertPair kaKeyAndCert = null;
        if (SignAlgo.DHPOP_X25519 == popAlg || SignAlgo.DHPOP_X448 == popAlg) {
            if (popControl != null) {
                DhSigStatic dhSigStatic = DhSigStatic.getInstance(popSign.getSignature().getBytes());
                IssuerAndSerialNumber isn = dhSigStatic.getIssuerAndSerial();
                ASN1ObjectIdentifier keyAlgOid = spki.getAlgorithm().getAlgorithm();
                kaKeyAndCert = popControl.getDhKeyCertPair(isn.getName(), isn.getSerialNumber().getValue(), EdECConstants.getName(keyAlgOid));
            }
            if (kaKeyAndCert == null) {
                return false;
            }
        }
        ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(publicKey, kaKeyAndCert);
        return certRequest.isValidSigningKeyPOP(cvp);
    } catch (InvalidKeyException | IllegalStateException | CRMFException ex) {
        LogUtil.error(LOG, ex);
    }
    return false;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) ProofOfPossession(org.bouncycastle.asn1.crmf.ProofOfPossession) DhSigStatic(org.bouncycastle.asn1.crmf.DhSigStatic) CRMFException(org.bouncycastle.cert.crmf.CRMFException) POPOSigningKey(org.bouncycastle.asn1.crmf.POPOSigningKey) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 17 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project xipki by xipki.

the class ScepResponder method servicePkiOperation0.

// method servicePkiOperation
private PkiMessage servicePkiOperation0(CMSSignedData requestContent, DecodedPkiMessage req, String certprofileName, String msgId, AuditEvent event) throws OperationException {
    notNull(requestContent, "requestContent");
    String tid = notNull(req, "req").getTransactionId().getId();
    // verify and decrypt the request
    audit(event, NAME_tid, tid);
    if (req.getFailureMessage() != null) {
        audit(event, Scep.NAME_failure_message, req.getFailureMessage());
    }
    Boolean bo = req.isSignatureValid();
    if (bo != null && !bo) {
        audit(event, Scep.NAME_signature, "invalid");
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo) {
        audit(event, Scep.NAME_decryption, "failed");
    }
    PkiMessage rep = new PkiMessage(req.getTransactionId(), MessageType.CertRep, Nonce.randomNonce());
    rep.setRecipientNonce(req.getSenderNonce());
    if (req.getFailureMessage() != null) {
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badRequest);
        return rep;
    }
    bo = req.isSignatureValid();
    if (bo != null && !bo) {
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badMessageCheck);
        return rep;
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo) {
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badRequest);
        return rep;
    }
    Date signingTime = req.getSigningTime();
    if (maxSigningTimeBiasInMs > 0) {
        boolean isTimeBad;
        if (signingTime == null) {
            isTimeBad = true;
        } else {
            long now = System.currentTimeMillis();
            long diff = now - signingTime.getTime();
            if (diff < 0) {
                diff = -1 * diff;
            }
            isTimeBad = diff > maxSigningTimeBiasInMs;
        }
        if (isTimeBad) {
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badTime);
            return rep;
        }
    }
    // end if
    // check the digest algorithm
    HashAlgo hashAlgo = req.getDigestAlgorithm();
    boolean supported = false;
    if (hashAlgo == HashAlgo.SHA1) {
        if (caCaps.supportsSHA1()) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA256) {
        if (caCaps.supportsSHA256()) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA512) {
        if (caCaps.supportsSHA512()) {
            supported = true;
        }
    }
    if (!supported) {
        LOG.warn("tid={}: unsupported digest algorithm {}", tid, hashAlgo);
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badAlg);
        return rep;
    }
    // check the content encryption algorithm
    ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
    if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
        if (!caCaps.supportsDES3()) {
            LOG.warn("tid={}: encryption with DES3 algorithm {} is not permitted", tid, encOid);
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badAlg);
            return rep;
        }
    } else if (CMSAlgorithm.AES128_CBC.equals(encOid)) {
        if (!caCaps.supportsAES()) {
            LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badAlg);
            return rep;
        }
    } else {
        LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badAlg);
        return rep;
    }
    X509Ca ca;
    try {
        ca = caManager.getX509Ca(caIdent);
    } catch (CaMgmtException ex) {
        LogUtil.error(LOG, ex, tid + "=" + tid + ",could not get X509CA");
        throw new OperationException(SYSTEM_FAILURE, ex);
    }
    X500Name caX500Name = ca.getCaInfo().getCert().getSubject();
    try {
        SignedData signedData;
        MessageType mt = req.getMessageType();
        audit(event, Scep.NAME_message_type, mt.toString());
        switch(mt) {
            case PKCSReq:
            case RenewalReq:
                CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
                X500Name reqSubject = csr.getCertificationRequestInfo().getSubject();
                if (LOG.isInfoEnabled()) {
                    LOG.info("tid={}, subject={}", tid, X509Util.getRfc4519Name(reqSubject));
                }
                if (!ca.verifyCsr(csr)) {
                    LOG.warn("tid={} POP verification failed", tid);
                    throw FailInfoException.BAD_MESSAGE_CHECK;
                }
                CertificationRequestInfo csrReqInfo = csr.getCertificationRequestInfo();
                X509Cert reqSignatureCert = req.getSignatureCert();
                X500Name reqSigCertSubject = reqSignatureCert.getSubject();
                boolean selfSigned = reqSignatureCert.isSelfSigned();
                if (selfSigned) {
                    if (!reqSigCertSubject.equals(csrReqInfo.getSubject())) {
                        LOG.warn("tid={}, self-signed identityCert.subject ({}) != csr.subject ({})", tid, reqSigCertSubject, csrReqInfo.getSubject());
                        throw FailInfoException.BAD_REQUEST;
                    }
                }
                if (X509Util.getCommonName(csrReqInfo.getSubject()) == null) {
                    throw new OperationException(BAD_CERT_TEMPLATE, "tid=" + tid + ": no CommonName in requested subject");
                }
                NameId userIdent = null;
                String challengePwd = CaUtil.getChallengePassword(csrReqInfo);
                if (challengePwd != null) {
                    String[] strs = challengePwd.split(":");
                    if (strs.length != 2) {
                        LOG.warn("tid={}: challengePassword does not have the format <user>:<password>", tid);
                        throw FailInfoException.BAD_REQUEST;
                    }
                    String user = strs[0];
                    String password = strs[1];
                    userIdent = ca.authenticateUser(user, StringUtil.toUtf8Bytes(password));
                    if (userIdent == null) {
                        LOG.warn("tid={}: could not authenticate user {}", tid, user);
                        throw FailInfoException.BAD_REQUEST;
                    }
                }
                if (selfSigned) {
                    if (MessageType.PKCSReq != mt) {
                        LOG.warn("tid={}: self-signed certificate is not permitted for" + " messageType {}", tid, mt);
                        throw FailInfoException.BAD_REQUEST;
                    }
                    if (userIdent == null) {
                        LOG.warn("tid={}: could not extract user & password from challengePassword" + ", which are required for self-signed signature certificate", tid);
                        throw FailInfoException.BAD_REQUEST;
                    }
                } else {
                    // certificate is known by the CA
                    if (userIdent == null) {
                        // up to draft-nourse-scep-23 the client sends all messages to enroll
                        // certificate via MessageType PKCSReq
                        KnowCertResult knowCertRes = ca.knowsCert(reqSignatureCert);
                        if (!knowCertRes.isKnown()) {
                            LOG.warn("tid={}: signature certificate is not trusted by the CA", tid);
                            throw FailInfoException.BAD_REQUEST;
                        }
                        Integer userId = knowCertRes.getUserId();
                        if (userId == null) {
                            LOG.warn("tid={}: could not extract user from the signature cert", tid);
                            throw FailInfoException.BAD_REQUEST;
                        }
                        userIdent = ca.getUserIdent(userId);
                    }
                // end if
                }
                // end if
                RequestorInfo.ByUserRequestorInfo requestor = ca.getByUserRequestor(userIdent);
                checkUserPermission(requestor, certprofileName);
                byte[] tidBytes = getTransactionIdBytes(tid);
                Extensions extensions = CaUtil.getExtensions(csrReqInfo);
                CertTemplateData certTemplateData = new CertTemplateData(csrReqInfo.getSubject(), csrReqInfo.getSubjectPublicKeyInfo(), null, null, extensions, certprofileName);
                CertificateInfo cert = ca.generateCert(certTemplateData, requestor, RequestType.SCEP, tidBytes, msgId);
                /* Don't save SCEP message, since it contains password in plaintext
          if (ca.getCaInfo().isSaveRequest() && cert.getCert().getCertId() != null) {
            byte[] encodedRequest;
            try {
              encodedRequest = requestContent.getEncoded();
            } catch (IOException ex) {
              LOG.warn("could not encode request");
              encodedRequest = null;
            }
            if (encodedRequest != null) {
              long reqId = ca.addRequest(encodedRequest);
              ca.addRequestCert(reqId, cert.getCert().getCertId());
            }
          }*/
                signedData = buildSignedData(cert.getCert().getCert());
                break;
            case CertPoll:
                IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
                audit(event, NAME_issuer, X509Util.getRfc4519Name(is.getIssuer()));
                audit(event, NAME_subject, X509Util.getRfc4519Name(is.getSubject()));
                ensureIssuedByThisCa(caX500Name, is.getIssuer());
                signedData = pollCert(ca, is.getSubject(), req.getTransactionId());
                break;
            case GetCert:
                IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
                BigInteger serial = isn.getSerialNumber().getPositiveValue();
                audit(event, NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
                audit(event, NAME_serial, LogUtil.formatCsn(serial));
                ensureIssuedByThisCa(caX500Name, isn.getName());
                signedData = getCert(ca, isn.getSerialNumber().getPositiveValue());
                break;
            case GetCRL:
                isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
                serial = isn.getSerialNumber().getPositiveValue();
                audit(event, NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
                audit(event, NAME_serial, LogUtil.formatCsn(serial));
                ensureIssuedByThisCa(caX500Name, isn.getName());
                signedData = getCrl(ca, serial);
                break;
            default:
                LOG.error("unknown SCEP messageType '{}'", req.getMessageType());
                throw FailInfoException.BAD_REQUEST;
        }
        // end switch
        ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);
        rep.setMessageData(ci);
        rep.setPkiStatus(PkiStatus.SUCCESS);
    } catch (FailInfoException ex) {
        LogUtil.error(LOG, ex);
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(ex.getFailInfo());
    }
    return rep;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) NameId(org.xipki.ca.api.NameId) HashAlgo(org.xipki.security.HashAlgo) X500Name(org.bouncycastle.asn1.x500.X500Name) KnowCertResult(org.xipki.ca.server.db.CertStore.KnowCertResult) Extensions(org.bouncycastle.asn1.x509.Extensions) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) X509Cert(org.xipki.security.X509Cert) CertificateInfo(org.xipki.ca.api.CertificateInfo) OperationException(org.xipki.ca.api.OperationException) SignedData(org.bouncycastle.asn1.cms.SignedData) Date(java.util.Date) BigInteger(java.math.BigInteger) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 18 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project xipki by xipki.

the class Client method scepGetCert.

// method scepGetCrl
public List<X509Cert> scepGetCert(PrivateKey identityKey, X509Cert identityCert, X500Name issuer, BigInteger serialNumber) throws ScepClientException {
    Args.notNull(identityKey, "identityKey");
    Args.notNull(identityCert, "identityCert");
    Args.notNull(issuer, "issuer");
    Args.notNull(serialNumber, "serialNumber");
    initIfNotInited();
    PkiMessage request = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCert);
    IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
    request.setMessageData(isn);
    ContentInfo envRequest = encryptThenSign(request, identityKey, identityCert);
    ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);
    CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
    DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
    if (response.getPkiStatus() != PkiStatus.SUCCESS) {
        throw new ScepClientException("server returned " + response.getPkiStatus());
    }
    ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());
    try {
        return ScepUtil.getCertsFromSignedData(SignedData.getInstance(messageData.getContent()));
    } catch (CertificateException ex) {
        throw new ScepClientException(ex.getMessage(), ex);
    }
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) CertificateException(java.security.cert.CertificateException) CMSSignedData(org.bouncycastle.cms.CMSSignedData)

Example 19 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project OpenPDF by LibrePDF.

the class PdfPublicKeySecurityHandler method computeRecipientInfo.

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificate tbsCertificate = TBSCertificate.getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbsCertificate.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbsCertificate.getIssuer(), tbsCertificate.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyTransRecipientInfo(org.bouncycastle.asn1.cms.KeyTransRecipientInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) Cipher(javax.crypto.Cipher) RecipientIdentifier(org.bouncycastle.asn1.cms.RecipientIdentifier) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 20 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project SORMAS-Project by hzi-braunschweig.

the class CmsCreator method createAttributes.

private static ASN1EncodableVector createAttributes(Certificate certificate) {
    ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(new IssuerAndSerialNumber(new X500Name(((X509Certificate) certificate).getIssuerDN().getName()), ((X509Certificate) certificate).getSerialNumber())));
    return attributes;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) SMIMEEncryptionKeyPreferenceAttribute(org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X500Name(org.bouncycastle.asn1.x500.X500Name)

Aggregations

IssuerAndSerialNumber (org.bouncycastle.asn1.cms.IssuerAndSerialNumber)21 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)7 CMSSignedData (org.bouncycastle.cms.CMSSignedData)5 IssuerAndSerialNumber (com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber)4 Date (java.util.Date)4 Cipher (javax.crypto.Cipher)4 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)4 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)4 DEROctetString (org.bouncycastle.asn1.DEROctetString)4 DhSigStatic (org.bouncycastle.asn1.crmf.DhSigStatic)4 CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)4 SMIMEEncryptionKeyPreferenceAttribute (org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 KeyTransRecipientInfo (org.bouncycastle.asn1.cms.KeyTransRecipientInfo)3 RecipientIdentifier (org.bouncycastle.asn1.cms.RecipientIdentifier)3 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 BigInteger (java.math.BigInteger)2