Search in sources :

Example 46 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class CmpCaClient method transmit.

private PKIMessage transmit(ProtectedPKIMessage request) throws Exception {
    byte[] encodedResponse = send(request.toASN1Structure().getEncoded());
    GeneralPKIMessage response = new GeneralPKIMessage(encodedResponse);
    PKIHeader reqHeader = request.getHeader();
    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();
    if (!tid.equals(respHeader.getTransactionID())) {
        throw new Exception("response.transactionId != request.transactionId");
    }
    ASN1OctetString senderNonce = reqHeader.getSenderNonce();
    if (!senderNonce.equals(respHeader.getRecipNonce())) {
        throw new Exception("response.recipientNonce != request.senderNonce");
    }
    GeneralName rec = respHeader.getRecipient();
    if (!requestorSubject.equals(rec)) {
        throw new Exception("unknown CMP requestor " + rec.toString());
    }
    if (!response.hasProtection()) {
        PKIBody respBody = response.getBody();
        int bodyType = respBody.getType();
        if (bodyType != PKIBody.TYPE_ERROR) {
            throw new Exception("response is not signed");
        }
    }
    if (verifyProtection(response)) {
        return response.toASN1Structure();
    }
    throw new Exception("invalid signature in PKI protection");
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMPException(org.bouncycastle.cert.cmp.CMPException) InvalidKeyException(java.security.InvalidKeyException) IOException(java.io.IOException) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage)

Example 47 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class CmpCaClient method verifyProtection.

// method extractGeneralRepContent
private boolean verifyProtection(GeneralPKIMessage pkiMessage) throws CMPException, InvalidKeyException {
    ProtectedPKIMessage protectedMsg = new ProtectedPKIMessage(pkiMessage);
    if (protectedMsg.hasPasswordBasedMacProtection()) {
        LOG.warn("protection is not signature based: " + pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return false;
    }
    PKIHeader header = protectedMsg.getHeader();
    if (!header.getSender().equals(responderSubject)) {
        LOG.warn("not authorized responder '{}'", header.getSender());
        return false;
    }
    String algOid = protectedMsg.getHeader().getProtectionAlg().getAlgorithm().getId();
    if (!trustedProtectionAlgOids.contains(algOid)) {
        LOG.warn("PKI protection algorithm is untrusted '{}'", algOid);
        return false;
    }
    ContentVerifierProvider verifierProvider = getContentVerifierProvider(responderCert.getPublicKey());
    if (verifierProvider == null) {
        LOG.warn("not authorized responder '{}'", header.getSender());
        return false;
    }
    return protectedMsg.verify(verifierProvider);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 48 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class P11ProxyResponder method processRequest.

/**
 * The request is constructed as follows:
 * <pre>
 * 0 - - - 1 - - - 2 - - - 3 - - - 4 - - - 5 - - - 6 - - - 7 - - - 8
 * |    Version    |        Transaction ID         |   Body ...    |
 * |   ... Length  |     Action    |   Module ID   |   Content...  |
 * |   .Content               | <-- 10 + Length (offset).
 *
 * </pre>
 */
byte[] processRequest(LocalP11CryptServicePool pool, byte[] request) {
    int reqLen = request.length;
    // TransactionID
    byte[] transactionId = new byte[4];
    if (reqLen > 5) {
        System.arraycopy(request, 2, transactionId, 0, 4);
    }
    // Action
    short action = P11ProxyConstants.ACTION_NOPE;
    if (reqLen > 11) {
        action = IoUtil.parseShort(request, 10);
    }
    if (reqLen < 14) {
        LOG.error("response too short");
        return getResp(P11ProxyConstants.VERSION_V1_0, transactionId, action, P11ProxyConstants.RC_BAD_REQUEST);
    }
    // Version
    short version = IoUtil.parseShort(request, 0);
    if (!versions.contains(version)) {
        LOG.error("unsupported version {}", version);
        return getResp(P11ProxyConstants.VERSION_V1_0, transactionId, action, P11ProxyConstants.RC_UNSUPPORTED_VERSION);
    }
    // Length
    int reqBodyLen = IoUtil.parseInt(request, 6);
    if (reqBodyLen + 10 != reqLen) {
        LOG.error("message length unmatch");
        return getResp(version, transactionId, action, P11ProxyConstants.RC_BAD_REQUEST);
    }
    short moduleId = IoUtil.parseShort(request, 12);
    int contentLen = reqLen - 14;
    byte[] content;
    if (contentLen == 0) {
        if (actionsRequireNonNullRequest.contains(action)) {
            LOG.error("content is not present but is required");
            return getResp(version, transactionId, P11ProxyConstants.RC_BAD_REQUEST, action);
        }
        content = null;
    } else {
        if (actionsRequireNullRequest.contains(action)) {
            LOG.error("content is present but is not permitted");
            return getResp(version, transactionId, P11ProxyConstants.RC_BAD_REQUEST, action);
        }
        content = new byte[contentLen];
        System.arraycopy(request, 14, content, 0, contentLen);
    }
    P11CryptService p11CryptService = pool.getP11CryptService(moduleId);
    if (p11CryptService == null) {
        LOG.error("no module {} available", moduleId);
        return getResp(version, transactionId, P11ProxyConstants.RC_UNKNOWN_MODULE, action);
    }
    try {
        switch(action) {
            case P11ProxyConstants.ACTION_ADD_CERT:
                {
                    Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
                    X509Certificate cert = X509Util.toX509Cert(asn1.getCertificate());
                    slot.addCert(asn1.getEntityId().getObjectId().getObjectId(), cert);
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            case P11ProxyConstants.ACTION_DIGEST_SECRETKEY:
                {
                    Asn1DigestSecretKeyTemplate template = Asn1DigestSecretKeyTemplate.getInstance(content);
                    long mechanism = template.getMechanism().getMechanism();
                    P11Identity identity = p11CryptService.getIdentity(template.getIdentityId().getEntityId());
                    byte[] hashValue = identity.digestSecretKey(mechanism);
                    ASN1Object obj = new DEROctetString(hashValue);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GEN_KEYPAIR_DSA:
                {
                    Asn1GenDSAKeypairParams asn1 = Asn1GenDSAKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.generateDSAKeypair(asn1.getP(), asn1.getQ(), asn1.getG(), asn1.getLabel(), asn1.getControl());
                    ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GEN_KEYPAIR_EC:
                {
                    Asn1GenECKeypairParams asn1 = Asn1GenECKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.generateECKeypair(asn1.getCurveId().getId(), asn1.getLabel(), asn1.getControl());
                    ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GEN_KEYPAIR_RSA:
                {
                    Asn1GenRSAKeypairParams asn1 = Asn1GenRSAKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.generateRSAKeypair(asn1.getKeysize(), asn1.getPublicExponent(), asn1.getLabel(), asn1.getControl());
                    ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GEN_KEYPAIR_SM2:
                {
                    Asn1GenSM2KeypairParams asn1 = Asn1GenSM2KeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.generateSM2Keypair(asn1.getLabel(), asn1.getControl());
                    ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GEN_SECRET_KEY:
                {
                    Asn1GenSecretKeyParams asn1 = Asn1GenSecretKeyParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.generateSecretKey(asn1.getKeyType(), asn1.getKeysize(), asn1.getLabel(), asn1.getControl());
                    ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GET_CERT:
                {
                    P11EntityIdentifier entityId = Asn1P11EntityIdentifier.getInstance(content).getEntityId();
                    X509Certificate cert = p11CryptService.getIdentity(entityId).getCertificate();
                    return getSuccessResp(version, transactionId, action, cert.getEncoded());
                }
            case P11ProxyConstants.ACTION_GET_CERT_IDS:
            case P11ProxyConstants.ACTION_GET_IDENTITY_IDS:
                {
                    Asn1P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(content);
                    P11Slot slot = p11CryptService.getModule().getSlot(slotId.getSlotId());
                    Set<P11ObjectIdentifier> objectIds;
                    if (P11ProxyConstants.ACTION_GET_CERT_IDS == action) {
                        objectIds = slot.getCertIdentifiers();
                    } else {
                        objectIds = slot.getIdentityIdentifiers();
                    }
                    ASN1EncodableVector vec = new ASN1EncodableVector();
                    for (P11ObjectIdentifier objectId : objectIds) {
                        vec.add(new Asn1P11ObjectIdentifier(objectId));
                    }
                    ASN1Object obj = new DERSequence(vec);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GET_MECHANISMS:
                {
                    P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(content).getSlotId();
                    Set<Long> mechs = p11CryptService.getSlot(slotId).getMechanisms();
                    ASN1EncodableVector vec = new ASN1EncodableVector();
                    for (Long mech : mechs) {
                        vec.add(new ASN1Integer(mech));
                    }
                    ASN1Object obj = new DERSequence(vec);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GET_PUBLICKEY:
                {
                    P11EntityIdentifier identityId = Asn1P11EntityIdentifier.getInstance(content).getEntityId();
                    PublicKey pubKey = p11CryptService.getIdentity(identityId).getPublicKey();
                    if (pubKey == null) {
                        throw new P11UnknownEntityException(identityId);
                    }
                    ASN1Object obj = KeyUtil.createSubjectPublicKeyInfo(pubKey);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GET_SERVER_CAPS:
                {
                    boolean readOnly = p11CryptService.getModule().isReadOnly();
                    ASN1Object obj = new Asn1ServerCaps(readOnly, versions);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_GET_SLOT_IDS:
                {
                    List<P11SlotIdentifier> slotIds = p11CryptService.getModule().getSlotIds();
                    ASN1EncodableVector vector = new ASN1EncodableVector();
                    for (P11SlotIdentifier slotId : slotIds) {
                        vector.add(new Asn1P11SlotIdentifier(slotId));
                    }
                    ASN1Object obj = new DERSequence(vector);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_IMPORT_SECRET_KEY:
                {
                    Asn1ImportSecretKeyParams asn1 = Asn1ImportSecretKeyParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.importSecretKey(asn1.getKeyType(), asn1.getKeyValue(), asn1.getLabel(), asn1.getControl());
                    ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_REMOVE_CERTS:
                {
                    Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1);
                    slot.removeCerts(asn1.getObjectId().getObjectId());
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            case P11ProxyConstants.ACTION_REMOVE_IDENTITY:
                {
                    Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1);
                    slot.removeIdentity(asn1.getObjectId().getObjectId());
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            case P11ProxyConstants.ACTION_REMOVE_OBJECTS:
                {
                    Asn1RemoveObjectsParams asn1 = Asn1RemoveObjectsParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    int num = slot.removeObjects(asn1.getOjectId(), asn1.getObjectLabel());
                    ASN1Object obj = new ASN1Integer(num);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_SIGN:
                {
                    Asn1SignTemplate signTemplate = Asn1SignTemplate.getInstance(content);
                    long mechanism = signTemplate.getMechanism().getMechanism();
                    Asn1P11Params asn1Params = signTemplate.getMechanism().getParams();
                    P11Params params = null;
                    if (asn1Params != null) {
                        switch(asn1Params.getTagNo()) {
                            case Asn1P11Params.TAG_RSA_PKCS_PSS:
                                params = Asn1RSAPkcsPssParams.getInstance(asn1Params).getPkcsPssParams();
                                break;
                            case Asn1P11Params.TAG_OPAQUE:
                                params = new P11ByteArrayParams(ASN1OctetString.getInstance(asn1Params).getOctets());
                                break;
                            case Asn1P11Params.TAG_IV:
                                params = new P11IVParams(ASN1OctetString.getInstance(asn1Params).getOctets());
                                break;
                            default:
                                throw new BadAsn1ObjectException("unknown SignTemplate.params: unknown tag " + asn1Params.getTagNo());
                        }
                    }
                    byte[] message = signTemplate.getMessage();
                    P11Identity identity = p11CryptService.getIdentity(signTemplate.getIdentityId().getEntityId());
                    byte[] signature = identity.sign(mechanism, params, message);
                    ASN1Object obj = new DEROctetString(signature);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case P11ProxyConstants.ACTION_UPDATE_CERT:
                {
                    Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
                    slot.updateCertificate(asn1.getEntityId().getObjectId().getObjectId(), X509Util.toX509Cert(asn1.getCertificate()));
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            default:
                {
                    LOG.error("unsupported XiPKI action code '{}'", action);
                    return getResp(version, transactionId, action, P11ProxyConstants.RC_UNSUPPORTED_ACTION);
                }
        }
    } catch (BadAsn1ObjectException ex) {
        LogUtil.error(LOG, ex, "could not process decode requested content (tid=" + Hex.encode(transactionId) + ")");
        return getResp(version, transactionId, action, P11ProxyConstants.RC_BAD_REQUEST);
    } catch (P11TokenException ex) {
        LogUtil.error(LOG, ex, buildErrorMsg(action, transactionId));
        short rc;
        if (ex instanceof P11UnknownEntityException) {
            rc = P11ProxyConstants.RC_DUPLICATE_ENTITY;
        } else if (ex instanceof P11DuplicateEntityException) {
            rc = P11ProxyConstants.RC_DUPLICATE_ENTITY;
        } else if (ex instanceof P11UnsupportedMechanismException) {
            rc = P11ProxyConstants.RC_UNSUPPORTED_MECHANISM;
        } else {
            rc = P11ProxyConstants.RC_P11_TOKENERROR;
        }
        return getResp(version, transactionId, action, rc);
    } catch (XiSecurityException | CertificateException | InvalidKeyException ex) {
        LogUtil.error(LOG, ex, buildErrorMsg(action, transactionId));
        return getResp(version, transactionId, action, P11ProxyConstants.RC_INTERNAL_ERROR);
    } catch (Throwable th) {
        LogUtil.error(LOG, th, buildErrorMsg(action, transactionId));
        return getResp(version, transactionId, action, P11ProxyConstants.RC_INTERNAL_ERROR);
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Asn1ServerCaps(org.xipki.p11proxy.msg.Asn1ServerCaps) P11TokenException(org.xipki.security.exception.P11TokenException) Asn1P11EntityIdentifier(org.xipki.p11proxy.msg.Asn1P11EntityIdentifier) P11EntityIdentifier(org.xipki.security.pkcs11.P11EntityIdentifier) CertificateException(java.security.cert.CertificateException) Asn1P11Params(org.xipki.p11proxy.msg.Asn1P11Params) P11Params(org.xipki.security.pkcs11.P11Params) Asn1RemoveObjectsParams(org.xipki.p11proxy.msg.Asn1RemoveObjectsParams) DEROctetString(org.bouncycastle.asn1.DEROctetString) P11DuplicateEntityException(org.xipki.security.exception.P11DuplicateEntityException) Asn1GenSecretKeyParams(org.xipki.p11proxy.msg.Asn1GenSecretKeyParams) Asn1P11EntityIdentifier(org.xipki.p11proxy.msg.Asn1P11EntityIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) XiSecurityException(org.xipki.security.exception.XiSecurityException) P11ByteArrayParams(org.xipki.security.pkcs11.P11ByteArrayParams) P11UnknownEntityException(org.xipki.security.exception.P11UnknownEntityException) Asn1DigestSecretKeyTemplate(org.xipki.p11proxy.msg.Asn1DigestSecretKeyTemplate) Asn1GenDSAKeypairParams(org.xipki.p11proxy.msg.Asn1GenDSAKeypairParams) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) Asn1ImportSecretKeyParams(org.xipki.p11proxy.msg.Asn1ImportSecretKeyParams) ASN1Object(org.bouncycastle.asn1.ASN1Object) Asn1P11Params(org.xipki.p11proxy.msg.Asn1P11Params) Asn1P11SlotIdentifier(org.xipki.p11proxy.msg.Asn1P11SlotIdentifier) P11SlotIdentifier(org.xipki.security.pkcs11.P11SlotIdentifier) PublicKey(java.security.PublicKey) Asn1SignTemplate(org.xipki.p11proxy.msg.Asn1SignTemplate) P11Slot(org.xipki.security.pkcs11.P11Slot) Asn1P11ObjectIdentifier(org.xipki.p11proxy.msg.Asn1P11ObjectIdentifier) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) P11Identity(org.xipki.security.pkcs11.P11Identity) InvalidKeyException(java.security.InvalidKeyException) P11CryptService(org.xipki.security.pkcs11.P11CryptService) X509Certificate(java.security.cert.X509Certificate) Asn1GenRSAKeypairParams(org.xipki.p11proxy.msg.Asn1GenRSAKeypairParams) Asn1EntityIdAndCert(org.xipki.p11proxy.msg.Asn1EntityIdAndCert) P11UnsupportedMechanismException(org.xipki.security.exception.P11UnsupportedMechanismException) Asn1GenSM2KeypairParams(org.xipki.p11proxy.msg.Asn1GenSM2KeypairParams) Asn1P11ObjectIdentifier(org.xipki.p11proxy.msg.Asn1P11ObjectIdentifier) P11ObjectIdentifier(org.xipki.security.pkcs11.P11ObjectIdentifier) Asn1GenECKeypairParams(org.xipki.p11proxy.msg.Asn1GenECKeypairParams) P11IVParams(org.xipki.security.pkcs11.P11IVParams) Asn1P11SlotIdentifier(org.xipki.p11proxy.msg.Asn1P11SlotIdentifier) BadAsn1ObjectException(org.xipki.security.exception.BadAsn1ObjectException)

Example 49 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class X509SelfSignedCertBuilder method generateSelfSigned.

public static GenerateSelfSignedResult generateSelfSigned(SecurityFactory securityFactory, String signerType, String signerConf, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException, InvalidConfException {
    ParamUtil.requireNonNull("securityFactory", securityFactory);
    ParamUtil.requireNonBlank("signerType", signerType);
    ParamUtil.requireNonNull("certprofile", certprofile);
    ParamUtil.requireNonNull("csr", csr);
    ParamUtil.requireNonNull("serialNumber", serialNumber);
    if (serialNumber.compareTo(BigInteger.ZERO) != 1) {
        throw new IllegalArgumentException("serialNumber must not be non-positive: " + serialNumber);
    }
    X509CertLevel level = certprofile.getCertLevel();
    if (X509CertLevel.RootCA != level) {
        throw new IllegalArgumentException("certprofile is not of level " + X509CertLevel.RootCA);
    }
    if (!securityFactory.verifyPopo(csr, null)) {
        throw new InvalidConfException("could not validate POP for the CSR");
    }
    if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) {
        ConfPairs keyValues = new ConfPairs(signerConf);
        String keystoreConf = keyValues.value("keystore");
        if (keystoreConf == null) {
            throw new InvalidConfException("required parameter 'keystore' for types PKCS12 and JKS, is not specified");
        }
    }
    ConcurrentContentSigner signer;
    try {
        List<String[]> signerConfs = CaEntry.splitCaSignerConfs(signerConf);
        List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms();
        String thisSignerConf = null;
        if (CollectionUtil.isEmpty(restrictedSigAlgos)) {
            thisSignerConf = signerConfs.get(0)[1];
        } else {
            for (String algo : restrictedSigAlgos) {
                for (String[] m : signerConfs) {
                    if (m[0].equals(algo)) {
                        thisSignerConf = m[1];
                        break;
                    }
                }
                if (thisSignerConf != null) {
                    break;
                }
            }
        }
        if (thisSignerConf == null) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
        }
        signer = securityFactory.createSigner(signerType, new SignerConf(thisSignerConf), (X509Certificate[]) null);
    } catch (XiSecurityException | ObjectCreationException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
    SubjectPublicKeyInfo publicKeyInfo;
    if (signer.getCertificate() != null) {
        // this cert is the dummy one which can be considered only as public key container
        Certificate bcCert;
        try {
            bcCert = Certificate.getInstance(signer.getCertificate().getEncoded());
        } catch (Exception ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not reparse certificate: " + ex.getMessage());
        }
        publicKeyInfo = bcCert.getSubjectPublicKeyInfo();
    } else {
        PublicKey signerPublicKey = signer.getPublicKey();
        try {
            publicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signerPublicKey);
        } catch (InvalidKeyException ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "cannot generate SubjectPublicKeyInfo from publicKey: " + ex.getMessage());
        }
    }
    X509Certificate newCert = generateCertificate(signer, certprofile, csr, serialNumber, publicKeyInfo, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
    return new GenerateSelfSignedResult(signerConf, newCert);
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) InvalidConfException(org.xipki.common.InvalidConfException) ConfPairs(org.xipki.common.ConfPairs) SignerConf(org.xipki.security.SignerConf) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertprofileException(org.xipki.ca.api.profile.CertprofileException) ObjectCreationException(org.xipki.common.ObjectCreationException) InvalidKeyException(java.security.InvalidKeyException) XiSecurityException(org.xipki.security.exception.XiSecurityException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) InvalidConfException(org.xipki.common.InvalidConfException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) OperationException(org.xipki.ca.api.OperationException) X509Certificate(java.security.cert.X509Certificate) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) XiSecurityException(org.xipki.security.exception.XiSecurityException) ObjectCreationException(org.xipki.common.ObjectCreationException) X509CertLevel(org.xipki.ca.api.profile.x509.X509CertLevel) OperationException(org.xipki.ca.api.OperationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 50 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class CmpResponder method processPkiMessage.

public PKIMessage processPkiMessage(PKIMessage pkiMessage, X509Certificate tlsClientCert, AuditEvent event) {
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);
    ParamUtil.requireNonNull("event", event);
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);
    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();
    String msgId = null;
    if (event != null) {
        msgId = RandomUtil.nextHexLong();
        event.addEventData(CaAuditConstants.NAME_mid, msgId);
    }
    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }
    String tidStr = Base64.encodeToString(tid.getOctets());
    if (event != null) {
        event.addEventData(CaAuditConstants.NAME_tid, tidStr);
    }
    int reqPvno = reqHeader.getPvno().getValue().intValue();
    if (reqPvno != PVNO_CMP2000) {
        if (event != null) {
            event.setLevel(AuditLevel.INFO);
            event.setStatus(AuditStatus.FAILED);
            event.addEventData(CaAuditConstants.NAME_message, "unsupproted version " + reqPvno);
        }
        return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.unsupportedVersion, null);
    }
    CmpControl cmpControl = getCmpControl();
    Integer failureCode = null;
    String statusText = null;
    Date messageTime = null;
    if (reqHeader.getMessageTime() != null) {
        try {
            messageTime = reqHeader.getMessageTime().getDate();
        } catch (ParseException ex) {
            LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not parse messageTime");
        }
    }
    GeneralName recipient = reqHeader.getRecipient();
    boolean intentMe = (recipient == null) ? true : intendsMe(recipient);
    if (!intentMe) {
        LOG.warn("tid={}: I am not the intended recipient, but '{}'", tid, reqHeader.getRecipient());
        failureCode = PKIFailureInfo.badRequest;
        statusText = "I am not the intended recipient";
    } else if (messageTime == null) {
        if (cmpControl.isMessageTimeRequired()) {
            failureCode = PKIFailureInfo.missingTimeStamp;
            statusText = "missing time-stamp";
        }
    } else {
        long messageTimeBias = cmpControl.getMessageTimeBias();
        if (messageTimeBias < 0) {
            messageTimeBias *= -1;
        }
        long msgTimeMs = messageTime.getTime();
        long currentTimeMs = System.currentTimeMillis();
        long bias = (msgTimeMs - currentTimeMs) / 1000L;
        if (bias > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message time is in the future";
        } else if (bias * -1 > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message too old";
        }
    }
    if (failureCode != null) {
        if (event != null) {
            event.setLevel(AuditLevel.INFO);
            event.setStatus(AuditStatus.FAILED);
            event.addEventData(CaAuditConstants.NAME_message, statusText);
        }
        return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText);
    }
    boolean isProtected = message.hasProtection();
    CmpRequestorInfo requestor;
    String errorStatus;
    if (isProtected) {
        try {
            ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl);
            ProtectionResult pr = verificationResult.getProtectionResult();
            switch(pr) {
                case VALID:
                    errorStatus = null;
                    break;
                case INVALID:
                    errorStatus = "request is protected by signature but invalid";
                    break;
                case NOT_SIGNATURE_BASED:
                    errorStatus = "request is not protected by signature";
                    break;
                case SENDER_NOT_AUTHORIZED:
                    errorStatus = "request is protected by signature but the requestor is not authorized";
                    break;
                case SIGALGO_FORBIDDEN:
                    errorStatus = "request is protected by signature but the protection algorithm" + " is forbidden";
                    break;
                default:
                    throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr);
            }
            // end switch
            requestor = (CmpRequestorInfo) verificationResult.getRequestor();
        } catch (Exception ex) {
            LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not verify the signature");
            errorStatus = "request has invalid signature based protection";
            requestor = null;
        }
    } else if (tlsClientCert != null) {
        boolean authorized = false;
        requestor = getRequestor(reqHeader);
        if (requestor != null) {
            if (tlsClientCert.equals(requestor.getCert().getCert())) {
                authorized = true;
            }
        }
        if (authorized) {
            errorStatus = null;
        } else {
            LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid, X509Util.getRfc4519Name(tlsClientCert.getSubjectX500Principal()));
            errorStatus = "requestor (TLS client certificate) is not authorized";
        }
    } else {
        errorStatus = "request has no protection";
        requestor = null;
    }
    if (errorStatus != null) {
        if (event != null) {
            event.setLevel(AuditLevel.INFO);
            event.setStatus(AuditStatus.FAILED);
            event.addEventData(CaAuditConstants.NAME_message, errorStatus);
        }
        return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus);
    }
    PKIMessage resp = processPkiMessage0(pkiMessage, requestor, tid, message, msgId, event);
    if (isProtected) {
        resp = addProtection(resp, event);
    } else {
    // protected by TLS connection
    }
    return resp;
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ProtectionResult(org.xipki.cmp.ProtectionResult) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) ProtectionVerificationResult(org.xipki.cmp.ProtectionVerificationResult) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMPException(org.bouncycastle.cert.cmp.CMPException) ParseException(java.text.ParseException) InvalidKeyException(java.security.InvalidKeyException) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) CmpControl(org.xipki.ca.server.mgmt.api.CmpControl) ParseException(java.text.ParseException) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Aggregations

IOException (java.io.IOException)58 DERIA5String (org.bouncycastle.asn1.DERIA5String)36 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)31 DERBitString (org.bouncycastle.asn1.DERBitString)31 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28 X509Certificate (java.security.cert.X509Certificate)28 SignatureException (java.security.SignatureException)27 DERSequence (org.bouncycastle.asn1.DERSequence)26 PublicKey (java.security.PublicKey)25 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)23 DEROctetString (org.bouncycastle.asn1.DEROctetString)22 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)22 Signature (java.security.Signature)21 CertificateException (java.security.cert.CertificateException)21 BigInteger (java.math.BigInteger)20 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)18 NoSuchProviderException (java.security.NoSuchProviderException)16