Search in sources :

Example 16 with Request

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

the class OcspServerImpl method init0.

private void init0() throws InvalidConfException, DataAccessException, PasswordResolverException {
    if (confFile == null) {
        throw new IllegalStateException("confFile is not set");
    }
    if (datasourceFactory == null) {
        throw new IllegalStateException("datasourceFactory is not set");
    }
    if (securityFactory == null) {
        throw new IllegalStateException("securityFactory is not set");
    }
    OCSPServer conf = parseConf(confFile);
    // -- check the duplication names
    Set<String> set = new HashSet<>();
    // Duplication name check: responder
    for (ResponderType m : conf.getResponders().getResponder()) {
        String name = m.getName();
        if (set.contains(name)) {
            throw new InvalidConfException("duplicated definition of responder named '" + name + "'");
        }
        if (StringUtil.isBlank(name)) {
            throw new InvalidConfException("responder name must not be empty");
        }
        for (int i = 0; i < name.length(); i++) {
            char ch = name.charAt(i);
            if (!((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '-') || ch == '_' || ch == '.') {
                throw new InvalidConfException("invalid OCSP responder name '" + name + "'");
            }
        }
        // end for
        set.add(name);
    }
    // end for
    // Duplication name check: signer
    set.clear();
    for (SignerType m : conf.getSigners().getSigner()) {
        String name = m.getName();
        if (set.contains(name)) {
            throw new InvalidConfException("duplicated definition of signer option named '" + name + "'");
        }
        set.add(name);
    }
    // Duplication name check: requests
    set.clear();
    for (RequestOptionType m : conf.getRequestOptions().getRequestOption()) {
        String name = m.getName();
        if (set.contains(name)) {
            throw new InvalidConfException("duplicated definition of request option named '" + name + "'");
        }
        set.add(name);
    }
    // Duplication name check: response
    set.clear();
    for (ResponseOptionType m : conf.getResponseOptions().getResponseOption()) {
        String name = m.getName();
        if (set.contains(name)) {
            throw new InvalidConfException("duplicated definition of response option named '" + name + "'");
        }
        set.add(name);
    }
    // Duplication name check: store
    set.clear();
    for (StoreType m : conf.getStores().getStore()) {
        String name = m.getName();
        if (set.contains(name)) {
            throw new InvalidConfException("duplicated definition of store named '" + name + "'");
        }
    }
    // Duplication name check: datasource
    set.clear();
    if (conf.getDatasources() != null) {
        for (DatasourceType m : conf.getDatasources().getDatasource()) {
            String name = m.getName();
            if (set.contains(name)) {
                throw new InvalidConfException("duplicated definition of datasource named '" + name + "'");
            }
            set.add(name);
        }
    }
    this.master = conf.isMaster();
    // Response Cache
    ResponseCacheType cacheType = conf.getResponseCache();
    if (cacheType != null) {
        DatasourceType cacheSourceConf = cacheType.getDatasource();
        DataSourceWrapper datasource;
        InputStream dsStream = null;
        try {
            dsStream = getInputStream(cacheSourceConf.getConf());
            datasource = datasourceFactory.createDataSource(cacheSourceConf.getName(), dsStream, securityFactory.getPasswordResolver());
        } catch (IOException ex) {
            throw new InvalidConfException(ex.getMessage(), ex);
        } finally {
            close(dsStream);
        }
        responseCacher = new ResponseCacher(datasource, master, cacheType.getValidity());
        responseCacher.init();
    }
    // signers
    for (SignerType m : conf.getSigners().getSigner()) {
        ResponderSigner signer = initSigner(m);
        signers.put(m.getName(), signer);
    }
    // requests
    for (RequestOptionType m : conf.getRequestOptions().getRequestOption()) {
        RequestOption option = new RequestOption(m);
        requestOptions.put(m.getName(), option);
    }
    // responses
    for (ResponseOptionType m : conf.getResponseOptions().getResponseOption()) {
        ResponseOption option = new ResponseOption(m);
        responseOptions.put(m.getName(), option);
    }
    // datasources
    Map<String, DataSourceWrapper> datasources = new HashMap<>();
    if (conf.getDatasources() != null) {
        for (DatasourceType m : conf.getDatasources().getDatasource()) {
            String name = m.getName();
            DataSourceWrapper datasource;
            InputStream dsStream = null;
            try {
                dsStream = getInputStream(m.getConf());
                datasource = datasourceFactory.createDataSource(name, dsStream, securityFactory.getPasswordResolver());
            } catch (IOException ex) {
                throw new InvalidConfException(ex.getMessage(), ex);
            } finally {
                close(dsStream);
            }
            datasources.put(name, datasource);
        }
    // end for
    }
    // end if
    // responders
    Map<String, ResponderOption> responderOptions = new HashMap<>();
    for (ResponderType m : conf.getResponders().getResponder()) {
        ResponderOption option = new ResponderOption(m);
        String optName = option.getSignerName();
        if (!signers.containsKey(optName)) {
            throw new InvalidConfException("no signer named '" + optName + "' is defined");
        }
        String reqOptName = option.getRequestOptionName();
        if (!requestOptions.containsKey(reqOptName)) {
            throw new InvalidConfException("no requestOption named '" + reqOptName + "' is defined");
        }
        String respOptName = option.getResponseOptionName();
        if (!responseOptions.containsKey(respOptName)) {
            throw new InvalidConfException("no responseOption named '" + respOptName + "' is defined");
        }
        // required HashAlgorithms for certificate
        List<StoreType> storeDefs = conf.getStores().getStore();
        Set<String> storeNames = new HashSet<>(storeDefs.size());
        for (StoreType storeDef : storeDefs) {
            storeNames.add(storeDef.getName());
        }
        responderOptions.put(m.getName(), option);
    }
    // stores
    for (StoreType m : conf.getStores().getStore()) {
        OcspStore store = newStore(m, datasources);
        stores.put(m.getName(), store);
    }
    // responders
    for (String name : responderOptions.keySet()) {
        ResponderOption option = responderOptions.get(name);
        List<OcspStore> statusStores = new ArrayList<>(option.getStoreNames().size());
        for (String storeName : option.getStoreNames()) {
            statusStores.add(stores.get(storeName));
        }
        ResponseOption responseOption = responseOptions.get(option.getResponseOptionName());
        ResponderSigner signer = signers.get(option.getSignerName());
        if (signer.isMacSigner()) {
            if (responseOption.isResponderIdByName()) {
                throw new InvalidConfException("could not use ResponderIdByName for signer " + option.getSignerName());
            }
            if (EmbedCertsMode.NONE != responseOption.getEmbedCertsMode()) {
                throw new InvalidConfException("could not embed certifcate in response for signer " + option.getSignerName());
            }
        }
        ResponderImpl responder = new ResponderImpl(option, requestOptions.get(option.getRequestOptionName()), responseOption, signer, statusStores);
        responders.put(name, responder);
    }
    // end for
    // servlet paths
    List<SizeComparableString> tmpList = new LinkedList<>();
    for (String name : responderOptions.keySet()) {
        ResponderImpl responder = responders.get(name);
        ResponderOption option = responderOptions.get(name);
        List<String> strs = option.getServletPaths();
        for (String path : strs) {
            tmpList.add(new SizeComparableString(path));
            path2responderMap.put(path, responder);
        }
    }
    // Sort the servlet paths according to the length of path. The first one is the
    // longest, and the last one is the shortest.
    Collections.sort(tmpList);
    List<String> list2 = new ArrayList<>(tmpList.size());
    for (SizeComparableString m : tmpList) {
        list2.add(m.str);
    }
    this.servletPaths = list2;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InvalidConfException(org.xipki.common.InvalidConfException) DatasourceType(org.xipki.ocsp.server.impl.jaxb.DatasourceType) SignerType(org.xipki.ocsp.server.impl.jaxb.SignerType) StoreType(org.xipki.ocsp.server.impl.jaxb.StoreType) OcspStore(org.xipki.ocsp.api.OcspStore) HashSet(java.util.HashSet) RequestOptionType(org.xipki.ocsp.server.impl.jaxb.RequestOptionType) ResponseOptionType(org.xipki.ocsp.server.impl.jaxb.ResponseOptionType) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ResponseCacheType(org.xipki.ocsp.server.impl.jaxb.ResponseCacheType) IOException(java.io.IOException) ResponderType(org.xipki.ocsp.server.impl.jaxb.ResponderType) LinkedList(java.util.LinkedList) OCSPServer(org.xipki.ocsp.server.impl.jaxb.OCSPServer) DataSourceWrapper(org.xipki.datasource.DataSourceWrapper)

Example 17 with Request

use of org.bouncycastle.asn1.ocsp.Request 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 18 with Request

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

the class CmpCaClient method requestCertViaCsr.

// method parseEnrollCertResult
public X509Certificate requestCertViaCsr(String certProfile, CertificationRequest csr) throws Exception {
    ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(PKIHeader.CMP_2000, requestorSubject, responderSubject);
    builder.setMessageTime(new Date());
    builder.setTransactionID(randomTransactionId());
    builder.setSenderNonce(randomSenderNonce());
    builder.addGeneralInfo(new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm, DERNull.INSTANCE));
    builder.addGeneralInfo(new InfoTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs, new DERUTF8String("CERT-PROFILE?" + certProfile + "%")));
    builder.setBody(new PKIBody(PKIBody.TYPE_P10_CERT_REQ, csr));
    ProtectedPKIMessage request = builder.build(requestorSigner);
    PKIMessage response = transmit(request);
    return parseEnrollCertResult(response);
}
Also used : ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) InfoTypeAndValue(org.bouncycastle.asn1.cmp.InfoTypeAndValue) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) ProtectedPKIMessageBuilder(org.bouncycastle.cert.cmp.ProtectedPKIMessageBuilder) Date(java.util.Date)

Example 19 with Request

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

the class CmpCaClient method send.

public byte[] send(byte[] request) throws IOException {
    SdkUtil.requireNonNull("request", request);
    HttpURLConnection httpUrlConnection = SdkUtil.openHttpConn(caUrl);
    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setUseCaches(false);
    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Content-Type", CMP_REQUEST_MIMETYPE);
    httpUrlConnection.setRequestProperty("Content-Length", Integer.toString(request.length));
    OutputStream outputstream = httpUrlConnection.getOutputStream();
    outputstream.write(request);
    outputstream.flush();
    InputStream inputStream = httpUrlConnection.getInputStream();
    if (httpUrlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        inputStream.close();
        throw new IOException("bad response: " + httpUrlConnection.getResponseCode() + "    " + httpUrlConnection.getResponseMessage());
    }
    String responseContentType = httpUrlConnection.getContentType();
    boolean isValidContentType = false;
    if (responseContentType != null) {
        if (responseContentType.equalsIgnoreCase(CMP_RESPONSE_MIMETYPE)) {
            isValidContentType = true;
        }
    }
    if (!isValidContentType) {
        inputStream.close();
        throw new IOException("bad response: mime type " + responseContentType + " not supported!");
    }
    return SdkUtil.read(inputStream);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String)

Example 20 with Request

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

the class OcspBenchRequestor method ask.

public void ask(BigInteger[] serialNumbers) throws OcspRequestorException {
    byte[] ocspReq = buildRequest(serialNumbers);
    int size = ocspReq.length;
    FullHttpRequest request;
    if (size <= MAX_LEN_GET && requestOptions.isUseHttpGetForRequest()) {
        String b64Request = Base64.encodeToString(ocspReq);
        String urlEncodedReq;
        try {
            urlEncodedReq = URLEncoder.encode(b64Request, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new OcspRequestorException(ex.getMessage());
        }
        String newRawpath = StringUtil.concat(responderRawPathGet, urlEncodedReq);
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, newRawpath);
    } else {
        ByteBuf content = Unpooled.wrappedBuffer(ocspReq);
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, responderRawPathPost, content);
        request.headers().addInt("Content-Length", content.readableBytes());
    }
    request.headers().add("Content-Type", "application/ocsp-request");
    httpClient.send(request);
}
Also used : OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

IOException (java.io.IOException)47 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)30 Date (java.util.Date)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 BigInteger (java.math.BigInteger)23 X509Certificate (java.security.cert.X509Certificate)22 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)22 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20 CertificateException (java.security.cert.CertificateException)18 ArrayList (java.util.ArrayList)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 Extension (org.bouncycastle.asn1.x509.Extension)16 Extensions (org.bouncycastle.asn1.x509.Extensions)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)15 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)13 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11