Search in sources :

Example 1 with StatusLine

use of org.openecard.apache.http.StatusLine in project open-ecard by ecsec.

the class HttpUtils method dumpHttpResponse.

/**
 * Dump the given HTTP response and log it with the given logger instance.
 * The response message is not modifyed by the method. If the data contained in the message should be printed, it
 * must be extracted seperately and provided in the respective parameter..
 *
 * @param logger Logger to dump HTTP request to.
 * @param res Response to dump.
 * @param entityData Response data to dump if not null.
 */
public static void dumpHttpResponse(@Nonnull Logger logger, @Nonnull HttpResponse res, @Nullable byte[] entityData) {
    if (logger.isDebugEnabled()) {
        StringWriter w = new StringWriter();
        PrintWriter pw = new PrintWriter(w);
        pw.println("HTTP Response:");
        StatusLine sl = res.getStatusLine();
        pw.format("  %s %d %s%n", sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase());
        for (Header h : res.getAllHeaders()) {
            pw.format("  %s: %s%n", h.getName(), h.getValue());
        }
        if (entityData != null) {
            pw.print(new String(entityData));
        }
        pw.println();
        pw.flush();
        logger.debug(w.toString());
    }
}
Also used : StatusLine(org.openecard.apache.http.StatusLine) StringWriter(java.io.StringWriter) Header(org.openecard.apache.http.Header) PrintWriter(java.io.PrintWriter)

Example 2 with StatusLine

use of org.openecard.apache.http.StatusLine in project open-ecard by ecsec.

the class ResourceContext method getStreamInt.

private static ResourceContext getStreamInt(URL url, CertificateValidator v, List<Pair<URL, TlsServerCertificate>> serverCerts, int maxRedirects) throws IOException, ResourceException, ValidationError, InvalidAddressException {
    try {
        DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
        CookieManager cManager = (CookieManager) dynCtx.get(TR03112Keys.COOKIE_MANAGER);
        LOG.info("Trying to load resource from: {}", url);
        if (maxRedirects == 0) {
            throw new ResourceException(MAX_REDIRECTS);
        }
        maxRedirects--;
        String protocol = url.getProtocol();
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
        }
        String resource = url.getFile();
        resource = resource.isEmpty() ? "/" : resource;
        if (!"https".equals(protocol)) {
            throw new InvalidAddressException(INVALID_ADDRESS);
        }
        // open a TLS connection, retrieve the server certificate and save it
        TlsClientProtocol h;
        DynamicAuthentication tlsAuth = new DynamicAuthentication(hostname);
        // add PKIX validator if not doin nPA auth
        if (isPKIXVerify()) {
            tlsAuth.addCertificateVerifier(new JavaSecVerifier());
        }
        // FIXME: validate certificate chain as soon as a usable solution exists for the trust problem
        // tlsAuth.setCertificateVerifier(new JavaSecVerifier());
        TlsCrypto crypto = new BcTlsCrypto(ReusableSecureRandom.getInstance());
        ClientCertTlsClient tlsClient = new ClientCertDefaultTlsClient(crypto, hostname, true);
        tlsClient.setAuthentication(tlsAuth);
        // connect tls client
        tlsClient.setClientVersion(ProtocolVersion.TLSv12);
        Socket socket = ProxySettings.getDefault().getSocket(protocol, hostname, port);
        h = new TlsClientProtocol(socket.getInputStream(), socket.getOutputStream());
        LOG.debug("Performing TLS handshake.");
        h.connect(tlsClient);
        LOG.debug("TLS handshake performed.");
        serverCerts.add(new Pair<>(url, tlsAuth.getServerCertificate()));
        // check result
        CertificateValidator.VerifierResult verifyResult = v.validate(url, tlsAuth.getServerCertificate());
        if (verifyResult == CertificateValidator.VerifierResult.FINISH) {
            List<Pair<URL, TlsServerCertificate>> pairs = Collections.unmodifiableList(serverCerts);
            return new ResourceContext(tlsClient, h, pairs);
        }
        StreamHttpClientConnection conn = new StreamHttpClientConnection(h.getInputStream(), h.getOutputStream());
        HttpContext ctx = new BasicHttpContext();
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("GET", resource);
        HttpRequestHelper.setDefaultHeader(req, url);
        req.setHeader("Accept", "text/xml, */*;q=0.8");
        req.setHeader("Accept-Charset", "utf-8, *;q=0.8");
        setCookieHeader(req, cManager, url);
        HttpUtils.dumpHttpRequest(LOG, req);
        LOG.debug("Sending HTTP request.");
        HttpResponse response = httpexecutor.execute(req, conn, ctx);
        storeCookies(response, cManager, url);
        LOG.debug("HTTP response received.");
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();
        String reason = status.getReasonPhrase();
        HttpUtils.dumpHttpResponse(LOG, response, null);
        HttpEntity entity = null;
        boolean finished = false;
        if (TR03112Utils.isRedirectStatusCode(statusCode)) {
            Header[] headers = response.getHeaders("Location");
            if (headers.length > 0) {
                String uri = headers[0].getValue();
                url = new URL(uri);
            } else {
                // FIXME: refactor exception handling
                throw new ResourceException(MISSING_LOCATION_HEADER);
            }
        } else if (statusCode >= 400) {
            // according to the HTTP RFC, codes greater than 400 signal errors
            LOG.debug("Received a result code {} '{}' from server.", statusCode, reason);
            throw new InvalidResultStatus(LANG.translationForKey(INVALID_RESULT_STATUS, statusCode, reason));
        } else {
            if (verifyResult == CertificateValidator.VerifierResult.CONTINUE) {
                throw new InvalidAddressException(INVALID_REFRESH_ADDRESS_NOSOP);
            } else {
                conn.receiveResponseEntity(response);
                entity = response.getEntity();
                finished = true;
            }
        }
        // follow next redirect or finish?
        if (finished) {
            assert (entity != null);
            ResourceContext result = new ResourceContext(tlsClient, h, serverCerts);
            LimitedInputStream is = new LimitedInputStream(entity.getContent());
            result.setStream(is);
            return result;
        } else {
            h.close();
            return getStreamInt(url, v, serverCerts, maxRedirects);
        }
    } catch (URISyntaxException ex) {
        throw new IOException(LANG.translationForKey(FAILED_PROXY), ex);
    } catch (HttpException ex) {
        // don't translate this, it is handled in the ActivationAction
        throw new IOException("Invalid HTTP message received.", ex);
    }
}
Also used : HttpRequestExecutor(org.openecard.apache.http.protocol.HttpRequestExecutor) HttpEntity(org.openecard.apache.http.HttpEntity) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) LimitedInputStream(org.openecard.common.io.LimitedInputStream) TlsClientProtocol(org.openecard.bouncycastle.tls.TlsClientProtocol) URISyntaxException(java.net.URISyntaxException) ClientCertTlsClient(org.openecard.crypto.tls.ClientCertTlsClient) StreamHttpClientConnection(org.openecard.transport.httpcore.StreamHttpClientConnection) URL(java.net.URL) TlsCrypto(org.openecard.bouncycastle.tls.crypto.TlsCrypto) BcTlsCrypto(org.openecard.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto) HttpException(org.openecard.apache.http.HttpException) CookieManager(org.openecard.transport.httpcore.cookies.CookieManager) JavaSecVerifier(org.openecard.crypto.tls.verify.JavaSecVerifier) InvalidResultStatus(org.openecard.transport.httpcore.InvalidResultStatus) Pair(org.openecard.common.util.Pair) BasicHttpEntityEnclosingRequest(org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) HttpContext(org.openecard.apache.http.protocol.HttpContext) ClientCertDefaultTlsClient(org.openecard.crypto.tls.ClientCertDefaultTlsClient) HttpResponse(org.openecard.apache.http.HttpResponse) BcTlsCrypto(org.openecard.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto) IOException(java.io.IOException) StatusLine(org.openecard.apache.http.StatusLine) Header(org.openecard.apache.http.Header) DynamicAuthentication(org.openecard.crypto.tls.auth.DynamicAuthentication) InvalidAddressException(org.openecard.binding.tctoken.ex.InvalidAddressException) Socket(java.net.Socket) DynamicContext(org.openecard.common.DynamicContext)

Example 3 with StatusLine

use of org.openecard.apache.http.StatusLine in project open-ecard by ecsec.

the class StatusLineResponseInterceptor method process.

@Override
public void process(HttpResponse hr, HttpContext hc) throws HttpException, IOException {
    StatusLine statusLine = hr.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    Locale locale = hr.getLocale();
    String reason = statusLine.getReasonPhrase();
    reason = reason != null ? reason : reasonForCode(statusCode, locale);
    hr.setStatusLine(new BasicStatusLine(statusLine.getProtocolVersion(), statusCode, reason));
}
Also used : BasicStatusLine(org.openecard.apache.http.message.BasicStatusLine) StatusLine(org.openecard.apache.http.StatusLine) Locale(java.util.Locale) BasicStatusLine(org.openecard.apache.http.message.BasicStatusLine)

Example 4 with StatusLine

use of org.openecard.apache.http.StatusLine in project open-ecard by ecsec.

the class ErrorResponseInterceptor method process.

@Override
public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (errorCodes.contains(statusCode)) {
        LOG.debug("HTTP response intercepted");
        Header contentType = httpResponse.getFirstHeader(HeaderTypes.CONTENT_TYPE.fieldName());
        if (contentType != null) {
            // Intercept response with the content type "text/plain"
            if (contentType.getValue().contains(MimeType.TEXT_PLAIN.getMimeType())) {
                // Remove old headers
                httpResponse.removeHeaders(HeaderTypes.CONTENT_TYPE.fieldName());
                httpResponse.removeHeaders(HeaderTypes.CONTENT_LENGTH.fieldName());
                // Read message body
                String content = readEntity(httpResponse.getEntity());
                // escape string to prevent script content to be injected into the template (XSS)
                content = HTMLUtils.escapeHtml(content);
                template.setProperty("%%%MESSAGE%%%", content);
            }
        } else {
            template.setProperty("%%%MESSAGE%%%", lang.translationForKey("http." + statusCode));
        }
        template.setProperty("%%%TITLE%%%", "Error");
        String reason = statusLine.getReasonPhrase();
        template.setProperty("%%%HEADLINE%%%", reason);
        // Add new content
        httpResponse.setEntity(new StringEntity(template.toString(), "UTF-8"));
        httpResponse.addHeader(HeaderTypes.CONTENT_TYPE.fieldName(), MimeType.TEXT_HTML.getMimeType() + "; charset=utf-8");
        httpResponse.addHeader(HeaderTypes.CONTENT_LENGTH.fieldName(), String.valueOf(template.getBytes().length));
    }
}
Also used : StatusLine(org.openecard.apache.http.StatusLine) StringEntity(org.openecard.apache.http.entity.StringEntity) Header(org.openecard.apache.http.Header)

Aggregations

StatusLine (org.openecard.apache.http.StatusLine)4 Header (org.openecard.apache.http.Header)3 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 Socket (java.net.Socket)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 Locale (java.util.Locale)1 HttpEntity (org.openecard.apache.http.HttpEntity)1 HttpException (org.openecard.apache.http.HttpException)1 HttpResponse (org.openecard.apache.http.HttpResponse)1 StringEntity (org.openecard.apache.http.entity.StringEntity)1 BasicHttpEntityEnclosingRequest (org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest)1 BasicStatusLine (org.openecard.apache.http.message.BasicStatusLine)1 BasicHttpContext (org.openecard.apache.http.protocol.BasicHttpContext)1 HttpContext (org.openecard.apache.http.protocol.HttpContext)1 HttpRequestExecutor (org.openecard.apache.http.protocol.HttpRequestExecutor)1 InvalidAddressException (org.openecard.binding.tctoken.ex.InvalidAddressException)1 TlsClientProtocol (org.openecard.bouncycastle.tls.TlsClientProtocol)1