Search in sources :

Example 1 with ZapGetMethod

use of org.zaproxy.zap.ZapGetMethod in project zaproxy by zaproxy.

the class HttpSender method send.

private void send(HttpMessage msg, boolean isFollowRedirect) throws IOException {
    HttpMethod method = null;
    HttpResponseHeader resHeader = null;
    try {
        method = runMethod(msg, isFollowRedirect);
        // successfully executed;
        resHeader = HttpMethodHelper.getHttpResponseHeader(method);
        // replaceAll("Transfer-Encoding: chunked\r\n",
        resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null);
        // "");
        msg.setResponseHeader(resHeader);
        msg.getResponseBody().setCharset(resHeader.getCharset());
        msg.getResponseBody().setLength(0);
        // ZAP: Moreover do not set content length to zero
        if (!msg.isEventStream()) {
            msg.getResponseBody().append(method.getResponseBody());
        }
        msg.setResponseFromTargetHost(true);
        // ZAP: set method to retrieve upgraded channel later
        if (method instanceof ZapGetMethod) {
            msg.setUserObject(method);
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}
Also used : ZapGetMethod(org.zaproxy.zap.ZapGetMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 2 with ZapGetMethod

use of org.zaproxy.zap.ZapGetMethod in project zaproxy by zaproxy.

the class HttpMethodHelper method createRequestMethod.

//  This is the currently in use method.
// may be replaced by the New method - however the New method is not yet fully tested so this is stil used.
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;
    String method = header.getMethod();
    URI uri = header.getURI();
    String version = header.getVersion();
    if (method == null || method.trim().length() < 3) {
        throw new URIException("Invalid HTTP method: " + method);
    }
    if (method.equalsIgnoreCase(GET)) {
        //httpMethod = new GetMethod();
        // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade 
        httpMethod = new ZapGetMethod();
    } else if (method.equalsIgnoreCase(POST)) {
        httpMethod = new ZapPostMethod();
    } else if (method.equalsIgnoreCase(DELETE)) {
        httpMethod = new ZapDeleteMethod();
    } else if (method.equalsIgnoreCase(PUT)) {
        httpMethod = new ZapPutMethod();
    } else if (method.equalsIgnoreCase(HEAD)) {
        httpMethod = new ZapHeadMethod();
    } else if (method.equalsIgnoreCase(OPTIONS)) {
        httpMethod = new ZapOptionsMethod();
    } else if (method.equalsIgnoreCase(TRACE)) {
        httpMethod = new ZapTraceMethod(uri.toString());
    } else {
        httpMethod = new GenericMethod(method);
    }
    try {
        httpMethod.setURI(uri);
    } catch (Exception e1) {
        throw new URIException("Failed to set URI [" + uri + "]: " + e1.getMessage());
    }
    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }
    // set various headers
    int pos = 0;
    // ZAP: changed to always use CRLF, like the HttpHeader
    Pattern pattern = patternCRLF;
    String delimiter = header.getLineDelimiter();
    // ZAP: Shouldn't happen as the HttpHeader always uses CRLF
    if (delimiter.equals(LF)) {
        delimiter = LF;
        pattern = patternLF;
    }
    String msg = header.getHeadersAsString();
    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }
        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    // set body if post method or put method
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        //			post.setRequestEntity(new StringRequestEntity(body.toString()));
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
Also used : ZapPutMethod(org.zaproxy.zap.network.ZapPutMethod) Pattern(java.util.regex.Pattern) ZapGetMethod(org.zaproxy.zap.ZapGetMethod) ZapTraceMethod(org.zaproxy.zap.network.ZapTraceMethod) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) ZapOptionsMethod(org.zaproxy.zap.network.ZapOptionsMethod) ZapHeadMethod(org.zaproxy.zap.network.ZapHeadMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(org.apache.commons.httpclient.URI) URIException(org.apache.commons.httpclient.URIException) URIException(org.apache.commons.httpclient.URIException) ZapPostMethod(org.zaproxy.zap.network.ZapPostMethod) ZapDeleteMethod(org.zaproxy.zap.network.ZapDeleteMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 3 with ZapGetMethod

use of org.zaproxy.zap.ZapGetMethod in project zaproxy by zaproxy.

the class ProxyThread method processHttp.

protected void processHttp(HttpRequestHeader requestHeader, boolean isSecure) throws IOException {
    // ZAP: Replaced the class HttpBody with the class HttpRequestBody.
    HttpRequestBody reqBody = null;
    boolean isFirstRequest = true;
    HttpMessage msg = null;
    // reduce socket timeout after first read
    inSocket.setSoTimeout(2500);
    do {
        if (isFirstRequest) {
            isFirstRequest = false;
        } else {
            try {
                requestHeader = httpIn.readRequestHeader(isSecure);
                requestHeader.setSenderAddress(inSocket.getInetAddress());
            } catch (SocketTimeoutException e) {
                // ZAP: Log the exception
                if (log.isDebugEnabled()) {
                    log.debug("Timed out while reading a new HTTP request.");
                }
                return;
            }
        }
        if (parentServer.isEnableApi() && API.getInstance().handleApiRequest(requestHeader, httpIn, httpOut, isRecursive(requestHeader))) {
            // It was an API request
            return;
        }
        msg = new HttpMessage();
        msg.setRequestHeader(requestHeader);
        if (msg.getRequestHeader().getContentLength() > 0) {
            // ZAP: Changed to call the method readRequestBody.
            reqBody = httpIn.readRequestBody(requestHeader);
            msg.setRequestBody(reqBody);
        }
        if (proxyParam.isRemoveUnsupportedEncodings()) {
            removeUnsupportedEncodings(msg);
        }
        if (isProcessCache(msg)) {
            continue;
        }
        if (parentServer.isSerialize()) {
            semaphore = semaphoreSingleton;
        } else {
            semaphore = this;
        }
        boolean send = true;
        synchronized (semaphore) {
            if (notifyOverrideListenersRequestSend(msg)) {
                send = false;
            } else if (!notifyListenerRequestSend(msg)) {
                // One of the listeners has told us to drop the request
                return;
            }
            try {
                //					getHttpSender().sendAndReceive(msg, httpOut, buffer);
                if (send) {
                    if (msg.getResponseHeader().isEmpty()) {
                        // Normally the response is empty.
                        // The only reason it wont be is if a script or other ext has deliberately 'hijacked' this request
                        // We dont jsut set send=false as this then means it wont appear in the History tab
                        getHttpSender().sendAndReceive(msg);
                    }
                    decodeResponseIfNeeded(msg);
                    if (!notifyOverrideListenersResponseReceived(msg)) {
                        if (!notifyListenerResponseReceive(msg)) {
                            // One of the listeners has told us to drop the response
                            return;
                        }
                    }
                }
            //			        notifyWrittenToForwardProxy();
            } catch (HttpException e) {
                //			    	System.out.println("HttpException");
                throw e;
            } catch (SocketTimeoutException e) {
                String message = Constant.messages.getString("proxy.error.readtimeout", msg.getRequestHeader().getURI(), connectionParam.getTimeoutInSecs());
                log.warn(message);
                setErrorResponse(msg, GATEWAY_TIMEOUT_RESPONSE_STATUS, message);
                notifyListenerResponseReceive(msg);
            } catch (IOException e) {
                setErrorResponse(msg, BAD_GATEWAY_RESPONSE_STATUS, e);
                notifyListenerResponseReceive(msg);
            //throw e;
            }
            try {
                writeHttpResponse(msg, httpOut);
            } catch (IOException e) {
                StringBuilder strBuilder = new StringBuilder(200);
                strBuilder.append("Failed to write/forward the HTTP response to the client: ");
                strBuilder.append(e.getClass().getName());
                if (e.getMessage() != null) {
                    strBuilder.append(": ").append(e.getMessage());
                }
                log.warn(strBuilder.toString());
            }
        }
        // release semaphore
        ZapGetMethod method = (ZapGetMethod) msg.getUserObject();
        keepSocketOpen = notifyPersistentConnectionListener(msg, inSocket, method);
        if (keepSocketOpen) {
            // do not wait for close
            break;
        }
    } while (!isConnectionClose(msg) && !inSocket.isClosed());
}
Also used : ZapGetMethod(org.zaproxy.zap.ZapGetMethod) HttpRequestBody(org.zaproxy.zap.network.HttpRequestBody) SocketTimeoutException(java.net.SocketTimeoutException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMessage(org.parosproxy.paros.network.HttpMessage)

Example 4 with ZapGetMethod

use of org.zaproxy.zap.ZapGetMethod in project zaproxy by zaproxy.

the class HttpPanelSender method handleSendMessage.

@Override
public void handleSendMessage(Message aMessage) throws IllegalArgumentException, IOException {
    final HttpMessage httpMessage = (HttpMessage) aMessage;
    try {
        final ModeRedirectionValidator redirectionValidator = new ModeRedirectionValidator();
        if (getButtonFollowRedirects().isSelected()) {
            getDelegate().sendAndReceive(httpMessage, redirectionValidator);
        } else {
            getDelegate().sendAndReceive(httpMessage, false);
        }
        EventQueue.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                if (!httpMessage.getResponseHeader().isEmpty()) {
                    // Indicate UI new response arrived
                    responsePanel.updateContent();
                    try {
                        Session session = Model.getSingleton().getSession();
                        HistoryReference ref = new HistoryReference(session, HistoryReference.TYPE_ZAP_USER, httpMessage);
                        final ExtensionHistory extHistory = getHistoryExtension();
                        if (extHistory != null) {
                            extHistory.addHistory(ref);
                        }
                        SessionStructure.addPath(session, ref, httpMessage);
                    } catch (final Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                    if (!redirectionValidator.isRequestValid()) {
                        View.getSingleton().showWarningDialog(Constant.messages.getString("manReq.outofscope.redirection.warning", redirectionValidator.getInvalidRedirection()));
                    }
                }
            }
        });
        ZapGetMethod method = (ZapGetMethod) httpMessage.getUserObject();
        notifyPersistentConnectionListener(httpMessage, null, method);
    } catch (final HttpMalformedHeaderException mhe) {
        throw new IllegalArgumentException("Malformed header error.", mhe);
    } catch (final UnknownHostException uhe) {
        throw new IOException("Error forwarding to an Unknown host: " + uhe.getMessage(), uhe);
    } catch (final SSLException sslEx) {
        throw sslEx;
    } catch (final IOException ioe) {
        throw new IOException("IO error in sending request: " + ioe.getClass() + ": " + ioe.getMessage(), ioe);
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
    }
}
Also used : ZapGetMethod(org.zaproxy.zap.ZapGetMethod) UnknownHostException(java.net.UnknownHostException) ExtensionHistory(org.parosproxy.paros.extension.history.ExtensionHistory) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SSLException(javax.net.ssl.SSLException) HistoryReference(org.parosproxy.paros.model.HistoryReference) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) HttpMessage(org.parosproxy.paros.network.HttpMessage) Session(org.parosproxy.paros.model.Session)

Aggregations

ZapGetMethod (org.zaproxy.zap.ZapGetMethod)4 IOException (java.io.IOException)2 HttpMethod (org.apache.commons.httpclient.HttpMethod)2 HttpMessage (org.parosproxy.paros.network.HttpMessage)2 SocketTimeoutException (java.net.SocketTimeoutException)1 UnknownHostException (java.net.UnknownHostException)1 Pattern (java.util.regex.Pattern)1 SSLException (javax.net.ssl.SSLException)1 HttpException (org.apache.commons.httpclient.HttpException)1 URI (org.apache.commons.httpclient.URI)1 URIException (org.apache.commons.httpclient.URIException)1 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)1 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)1 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)1 ExtensionHistory (org.parosproxy.paros.extension.history.ExtensionHistory)1 HistoryReference (org.parosproxy.paros.model.HistoryReference)1 Session (org.parosproxy.paros.model.Session)1 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)1 HttpRequestBody (org.zaproxy.zap.network.HttpRequestBody)1 ZapDeleteMethod (org.zaproxy.zap.network.ZapDeleteMethod)1