Search in sources :

Example 11 with HttpMessage

use of org.parosproxy.paros.network.HttpMessage in project zaproxy by zaproxy.

the class ExtensionAntiCSRF method generateForm.

public String generateForm(int hrefId) throws Exception {
    ExtensionHistory extHist = (ExtensionHistory) Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.NAME);
    if (extHist != null) {
        HistoryReference hr = extHist.getHistoryReference(hrefId);
        if (hr == null) {
            return null;
        }
        HttpMessage msg = hr.getHttpMessage();
        StringBuilder sb = new StringBuilder(300);
        sb.append("<html>\n");
        sb.append("<body>\n");
        sb.append("<h3>");
        sb.append(msg.getRequestHeader().getURI());
        sb.append("</h3>");
        sb.append("<form id=\"f1\" method=\"POST\" action=\"" + hr.getURI() + "\">\n");
        sb.append("<table>\n");
        TreeSet<HtmlParameter> params = msg.getFormParams();
        // Let the message be GC'ed as it's no longer needed.
        msg = null;
        Iterator<HtmlParameter> iter = params.iterator();
        while (iter.hasNext()) {
            HtmlParameter htmlParam = iter.next();
            String name = URLDecoder.decode(htmlParam.getName(), "UTF-8");
            String value = URLDecoder.decode(htmlParam.getValue(), "UTF-8");
            sb.append("<tr><td>\n");
            sb.append(name);
            sb.append("<td>");
            sb.append("<input name=\"");
            sb.append(name);
            sb.append("\" value=\"");
            sb.append(value);
            sb.append("\" size=\"100\">");
            sb.append("</tr>\n");
        }
        sb.append("</table>\n");
        sb.append("<input id=\"submit\" type=\"submit\" value=\"Submit\"/>\n");
        sb.append("</form>\n");
        sb.append("</body>\n");
        sb.append("</html>\n");
        return sb.toString();
    }
    return null;
}
Also used : HistoryReference(org.parosproxy.paros.model.HistoryReference) ExtensionHistory(org.parosproxy.paros.extension.history.ExtensionHistory) HtmlParameter(org.parosproxy.paros.network.HtmlParameter) HttpMessage(org.parosproxy.paros.network.HttpMessage)

Example 12 with HttpMessage

use of org.parosproxy.paros.network.HttpMessage in project zaproxy by zaproxy.

the class API method handleApiRequest.

public boolean handleApiRequest(HttpRequestHeader requestHeader, HttpInputStream httpIn, HttpOutputStream httpOut, boolean force) throws IOException {
    String url = requestHeader.getURI().toString();
    Format format = Format.OTHER;
    ApiImplementor callbackImpl = null;
    ApiImplementor shortcutImpl = null;
    // Check for callbacks
    if (url.contains(CALL_BACK_URL)) {
        if (!isPermittedAddr(requestHeader)) {
            return true;
        }
        logger.debug("handleApiRequest Callback: " + url);
        for (Entry<String, ApiImplementor> callback : callBacks.entrySet()) {
            if (url.startsWith(callback.getKey())) {
                callbackImpl = callback.getValue();
                break;
            }
        }
    }
    String path = requestHeader.getURI().getPath();
    if (path != null) {
        for (Entry<String, ApiImplementor> shortcut : shortcuts.entrySet()) {
            if (path.startsWith(shortcut.getKey())) {
                shortcutImpl = shortcut.getValue();
                break;
            }
        }
    }
    if (shortcutImpl == null && callbackImpl == null && !url.startsWith(API_URL) && !url.startsWith(API_URL_S) && !force) {
        return false;
    }
    if (!isPermittedAddr(requestHeader)) {
        return true;
    }
    if (getOptionsParamApi().isSecureOnly() && !requestHeader.isSecure()) {
        // Insecure request with secure only set, always ignore
        logger.debug("handleApiRequest rejecting insecure request");
        return true;
    }
    logger.debug("handleApiRequest " + url);
    HttpMessage msg = new HttpMessage();
    msg.setRequestHeader(requestHeader);
    if (requestHeader.getContentLength() > 0) {
        msg.setRequestBody(httpIn.readRequestBody(requestHeader));
    }
    String component = null;
    ApiImplementor impl = null;
    RequestType reqType = null;
    String contentType = "text/plain; charset=UTF-8";
    String response = "";
    String name = null;
    boolean error = false;
    try {
        JSONObject params = getParams(requestHeader.getURI().getEscapedQuery());
        if (shortcutImpl != null) {
            if (!getOptionsParamApi().isDisableKey() && !getOptionsParamApi().isNoKeyForSafeOps()) {
                if (!this.hasValidKey(requestHeader, params)) {
                    throw new ApiException(ApiException.Type.BAD_API_KEY);
                }
            }
            msg = shortcutImpl.handleShortcut(msg);
        } else if (callbackImpl != null) {
            // Callbacks have suitably random URLs and therefore don't require keys/nonces
            response = callbackImpl.handleCallBack(msg);
        } else {
            // Parse the query:
            // format of url is http://zap/format/component/reqtype/name/?params
            //                    0  1  2    3        4        5      6
            String[] elements = url.split("/");
            if (elements.length > 3 && elements[3].equalsIgnoreCase("favicon.ico")) {
                // Treat the favicon as a special case:)
                if (!getOptionsParamApi().isUiEnabled()) {
                    throw new ApiException(ApiException.Type.DISABLED);
                }
                InputStream is = API.class.getResourceAsStream("/resource/zap.ico");
                byte[] icon = new byte[is.available()];
                is.read(icon);
                is.close();
                msg.setResponseHeader(getDefaultResponseHeader(contentType));
                msg.getResponseHeader().setContentLength(icon.length);
                httpOut.write(msg.getResponseHeader());
                httpOut.write(icon);
                httpOut.flush();
                httpOut.close();
                httpIn.close();
                return true;
            } else if (elements.length > 3) {
                try {
                    format = Format.valueOf(elements[3].toUpperCase());
                    switch(format) {
                        case JSON:
                            contentType = "application/json; charset=UTF-8";
                            break;
                        case JSONP:
                            contentType = "application/javascript; charset=UTF-8";
                            break;
                        case XML:
                            contentType = "text/xml; charset=UTF-8";
                            break;
                        case HTML:
                            contentType = "text/html; charset=UTF-8";
                            break;
                        case UI:
                            contentType = "text/html; charset=UTF-8";
                            break;
                        default:
                            break;
                    }
                } catch (IllegalArgumentException e) {
                    format = Format.HTML;
                    throw new ApiException(ApiException.Type.BAD_FORMAT);
                }
            }
            if (elements.length > 4) {
                component = elements[4];
                impl = implementors.get(component);
                if (impl == null) {
                    throw new ApiException(ApiException.Type.NO_IMPLEMENTOR);
                }
            }
            if (elements.length > 5) {
                try {
                    reqType = RequestType.valueOf(elements[5]);
                } catch (IllegalArgumentException e) {
                    throw new ApiException(ApiException.Type.BAD_TYPE);
                }
            }
            if (elements.length > 6) {
                name = elements[6];
                if (name != null && name.indexOf("?") > 0) {
                    name = name.substring(0, name.indexOf("?"));
                }
            }
            if (format.equals(Format.UI)) {
                if (!isEnabled() || !getOptionsParamApi().isUiEnabled()) {
                    throw new ApiException(ApiException.Type.DISABLED);
                }
                response = webUI.handleRequest(component, impl, reqType, name);
                contentType = "text/html; charset=UTF-8";
            } else if (name != null) {
                if (!isEnabled()) {
                    throw new ApiException(ApiException.Type.DISABLED);
                }
                // Do this now as it might contain the api key/nonce
                if (requestHeader.getMethod().equalsIgnoreCase(HttpRequestHeader.POST)) {
                    String contentTypeHeader = requestHeader.getHeader(HttpHeader.CONTENT_TYPE);
                    if (contentTypeHeader != null && contentTypeHeader.equals(HttpHeader.FORM_URLENCODED_CONTENT_TYPE)) {
                        params = getParams(msg.getRequestBody().toString());
                    } else {
                        throw new ApiException(ApiException.Type.CONTENT_TYPE_NOT_SUPPORTED);
                    }
                }
                if (format.equals(Format.JSONP)) {
                    if (!getOptionsParamApi().isEnableJSONP()) {
                        // Not enabled
                        throw new ApiException(ApiException.Type.DISABLED);
                    }
                    if (!this.hasValidKey(requestHeader, params)) {
                        // An api key is required for ALL JSONP requests
                        throw new ApiException(ApiException.Type.BAD_API_KEY);
                    }
                }
                ApiResponse res;
                switch(reqType) {
                    case action:
                        if (!getOptionsParamApi().isDisableKey()) {
                            if (!this.hasValidKey(requestHeader, params)) {
                                throw new ApiException(ApiException.Type.BAD_API_KEY);
                            }
                        }
                        ApiAction action = impl.getApiAction(name);
                        if (action != null) {
                            // Checking for null to handle option actions
                            List<String> mandatoryParams = action.getMandatoryParamNames();
                            if (mandatoryParams != null) {
                                for (String param : mandatoryParams) {
                                    if (!params.has(param) || params.getString(param).length() == 0) {
                                        throw new ApiException(ApiException.Type.MISSING_PARAMETER, param);
                                    }
                                }
                            }
                        }
                        res = impl.handleApiOptionAction(name, params);
                        if (res == null) {
                            res = impl.handleApiAction(name, params);
                        }
                        switch(format) {
                            case JSON:
                                response = res.toJSON().toString();
                                break;
                            case JSONP:
                                response = this.getJsonpWrapper(res.toJSON().toString());
                                break;
                            case XML:
                                response = this.responseToXml(name, res);
                                break;
                            case HTML:
                                response = this.responseToHtml(name, res);
                                break;
                            default:
                                break;
                        }
                        break;
                    case view:
                        if (!getOptionsParamApi().isDisableKey() && !getOptionsParamApi().isNoKeyForSafeOps()) {
                            if (!this.hasValidKey(requestHeader, params)) {
                                throw new ApiException(ApiException.Type.BAD_API_KEY);
                            }
                        }
                        ApiView view = impl.getApiView(name);
                        if (view != null) {
                            // Checking for null to handle option actions
                            List<String> mandatoryParams = view.getMandatoryParamNames();
                            if (mandatoryParams != null) {
                                for (String param : mandatoryParams) {
                                    if (!params.has(param) || params.getString(param).length() == 0) {
                                        throw new ApiException(ApiException.Type.MISSING_PARAMETER, param);
                                    }
                                }
                            }
                        }
                        res = impl.handleApiOptionView(name, params);
                        if (res == null) {
                            res = impl.handleApiView(name, params);
                        }
                        switch(format) {
                            case JSON:
                                response = res.toJSON().toString();
                                break;
                            case JSONP:
                                response = this.getJsonpWrapper(res.toJSON().toString());
                                break;
                            case XML:
                                response = this.responseToXml(name, res);
                                break;
                            case HTML:
                                response = this.responseToHtml(name, res);
                                break;
                            default:
                                break;
                        }
                        break;
                    case other:
                        ApiOther other = impl.getApiOther(name);
                        if (other != null) {
                            // Checking for null to handle option actions
                            if (!getOptionsParamApi().isDisableKey() && (!getOptionsParamApi().isNoKeyForSafeOps() || other.isRequiresApiKey())) {
                                // Check if a valid api key has been used
                                if (!this.hasValidKey(requestHeader, params)) {
                                    throw new ApiException(ApiException.Type.BAD_API_KEY);
                                }
                            }
                            List<String> mandatoryParams = other.getMandatoryParamNames();
                            if (mandatoryParams != null) {
                                for (String param : mandatoryParams) {
                                    if (!params.has(param) || params.getString(param).length() == 0) {
                                        throw new ApiException(ApiException.Type.MISSING_PARAMETER, param);
                                    }
                                }
                            }
                        }
                        msg = impl.handleApiOther(msg, name, params);
                }
            } else {
                // Handle default front page, unless if the API UI is disabled
                if (!isEnabled() || !getOptionsParamApi().isUiEnabled()) {
                    throw new ApiException(ApiException.Type.DISABLED);
                }
                response = webUI.handleRequest(requestHeader.getURI(), this.isEnabled());
                format = Format.UI;
                contentType = "text/html; charset=UTF-8";
            }
        }
        logger.debug("handleApiRequest returning: " + response);
    } catch (Exception e) {
        if (!getOptionsParamApi().isReportPermErrors()) {
            if (e instanceof ApiException) {
                ApiException exception = (ApiException) e;
                if (exception.getType().equals(ApiException.Type.DISABLED) || exception.getType().equals(ApiException.Type.BAD_API_KEY)) {
                    // Fail silently
                    return true;
                }
            }
        }
        handleException(msg, format, contentType, e);
        error = true;
    }
    if (!error && !format.equals(Format.OTHER) && shortcutImpl == null) {
        msg.setResponseHeader(getDefaultResponseHeader(contentType));
        msg.setResponseBody(response);
        msg.getResponseHeader().setContentLength(msg.getResponseBody().length());
    }
    if (impl != null) {
        impl.addCustomHeaders(name, reqType, msg);
    }
    httpOut.write(msg.getResponseHeader());
    httpOut.write(msg.getResponseBody().getBytes());
    httpOut.flush();
    httpOut.close();
    httpIn.close();
    return true;
}
Also used : HttpInputStream(org.parosproxy.paros.network.HttpInputStream) InputStream(java.io.InputStream) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(net.sf.json.JSONObject) HttpMessage(org.parosproxy.paros.network.HttpMessage)

Example 13 with HttpMessage

use of org.parosproxy.paros.network.HttpMessage in project zaproxy by zaproxy.

the class AlertViewPanel method getAlert.

public Alert getAlert() {
    if (!editable && originalAlert != null) {
        Alert alert = originalAlert.newInstance();
        alert.setAlertId(originalAlert.getAlertId());
        alert.setName((String) alertEditName.getSelectedItem());
        alert.setParam((String) alertEditParam.getSelectedItem());
        alert.setRiskConfidence(alertEditRisk.getSelectedIndex(), alertEditConfidence.getSelectedIndex());
        alert.setDescription(alertDescription.getText());
        alert.setOtherInfo(alertOtherInfo.getText());
        alert.setSolution(alertSolution.getText());
        alert.setReference(alertReference.getText());
        alert.setEvidence(alertEvidence.getText());
        alert.setCweId(alertEditCweId.getValue());
        alert.setWascId(alertEditWascId.getValue());
        alert.setHistoryRef(historyRef);
        return alert;
    }
    Alert alert = new Alert(-1, alertEditRisk.getSelectedIndex(), alertEditConfidence.getSelectedIndex(), (String) alertEditName.getSelectedItem());
    alert.setHistoryRef(historyRef);
    if (originalAlert != null) {
        alert.setAlertId(originalAlert.getAlertId());
        alert.setSource(originalAlert.getSource());
    }
    String uri = null;
    HttpMessage msg = null;
    if (httpMessage != null) {
        uri = httpMessage.getRequestHeader().getURI().toString();
        msg = httpMessage;
    } else if (historyRef != null) {
        try {
            uri = historyRef.getURI().toString();
            msg = historyRef.getHttpMessage();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    } else if (originalAlert != null) {
        uri = originalAlert.getUri();
        msg = originalAlert.getMessage();
    }
    alert.setDetail(alertDescription.getText(), uri, (String) alertEditParam.getSelectedItem(), alertEditAttack.getText(), alertOtherInfo.getText(), alertSolution.getText(), alertReference.getText(), alertEditEvidence.getText(), alertEditCweId.getValue(), alertEditWascId.getValue(), msg);
    return alert;
}
Also used : Alert(org.parosproxy.paros.core.scanner.Alert) HttpMessage(org.parosproxy.paros.network.HttpMessage)

Example 14 with HttpMessage

use of org.parosproxy.paros.network.HttpMessage in project zaproxy by zaproxy.

the class ExtensionAutoUpdate method getRemoteConfigurationUrl.

private ZapXmlConfiguration getRemoteConfigurationUrl(String url) throws IOException, ConfigurationException, InvalidCfuUrlException {
    HttpMessage msg = new HttpMessage(new URI(url, true), Model.getSingleton().getOptionsParam().getConnectionParam());
    getHttpSender().sendAndReceive(msg, true);
    if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
        throw new IOException();
    }
    if (!msg.getRequestHeader().isSecure()) {
        // Only access the cfu page over https
        throw new InvalidCfuUrlException(msg.getRequestHeader().getURI().toString());
    }
    ZapXmlConfiguration config = new ZapXmlConfiguration();
    config.setDelimiterParsingDisabled(true);
    config.load(new StringReader(msg.getResponseBody().toString()));
    // Save version file so we can report new addons next time
    File f = new File(Constant.FOLDER_LOCAL_PLUGIN, VERSION_FILE_NAME);
    FileWriter out = null;
    try {
        out = new FileWriter(f);
        out.write(msg.getResponseBody().toString());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
        // Ignore
        }
    }
    return config;
}
Also used : FileWriter(java.io.FileWriter) StringReader(java.io.StringReader) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) IOException(java.io.IOException) HttpMessage(org.parosproxy.paros.network.HttpMessage) URI(org.apache.commons.httpclient.URI) File(java.io.File) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException)

Example 15 with HttpMessage

use of org.parosproxy.paros.network.HttpMessage in project zaproxy by zaproxy.

the class BreakAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    if (ACTION_BREAK.equals(name)) {
        String type = params.getString(PARAM_TYPE).toLowerCase();
        if (type.equals(VALUE_TYPE_HTTP_ALL)) {
            extension.setBreakAllRequests(params.getBoolean(PARAM_STATE));
            extension.setBreakAllResponses(params.getBoolean(PARAM_STATE));
        } else if (type.equals(VALUE_TYPE_HTTP_REQUESTS)) {
            extension.setBreakAllRequests(params.getBoolean(PARAM_STATE));
        } else if (type.equals(VALUE_TYPE_HTTP_RESPONSES)) {
            extension.setBreakAllResponses(params.getBoolean(PARAM_STATE));
        } else {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_TYPE + " not in [" + VALUE_TYPE_HTTP_ALL + "," + VALUE_TYPE_HTTP_REQUESTS + "," + VALUE_TYPE_HTTP_RESPONSES + "]");
        }
    } else if (ACTION_BREAK_ON_ID.equals(name)) {
        extension.setBreakOnId(params.getString(PARAM_KEY), params.getString(PARAM_STATE).toLowerCase().equals("on"));
    } else if (ACTION_CONTINUE.equals(name)) {
        extension.getBreakpointManagementInterface().cont();
    } else if (ACTION_STEP.equals(name)) {
        extension.getBreakpointManagementInterface().step();
    } else if (ACTION_DROP.equals(name)) {
        extension.getBreakpointManagementInterface().drop();
    } else if (ACTION_SET_HTTP_MESSAGE.equals(name)) {
        if (extension.getBreakpointManagementInterface().getMessage() == null) {
            // We've not got an intercepted message
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
        }
        String header = params.getString(PARAM_HTTP_HEADER);
        String body = this.getParam(params, PARAM_HTTP_BODY, "");
        if (header.indexOf(HttpHeader.CRLF) < 0) {
            if (header.indexOf("\\n") >= 0) {
                // Makes it easier to use via API UI
                header = header.replace("\\r", "\r").replace("\\n", "\n");
            }
        }
        Message msg = extension.getBreakpointManagementInterface().getMessage();
        if (msg instanceof HttpMessage) {
            HttpMessage httpMsg = (HttpMessage) msg;
            if (extension.getBreakpointManagementInterface().isRequest()) {
                try {
                    httpMsg.setRequestHeader(header);
                    httpMsg.setRequestBody(body);
                    extension.getBreakpointManagementInterface().setMessage(httpMsg, true);
                } catch (HttpMalformedHeaderException e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, e.getMessage());
                }
            } else {
                try {
                    httpMsg.setResponseHeader(header);
                    httpMsg.setResponseBody(body);
                    extension.getBreakpointManagementInterface().setMessage(httpMsg, false);
                } catch (HttpMalformedHeaderException e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, e.getMessage());
                }
            }
        }
    } else if (ACTION_ADD_HTTP_BREAK_POINT.equals(name)) {
        try {
            extension.addHttpBreakpoint(params.getString(PARAM_STRING), params.getString(PARAM_LOCATION), params.getString(PARAM_MATCH), params.getBoolean(PARAM_INVERSE), params.getBoolean(PARAM_IGNORECASE));
        } catch (Exception e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, e.getMessage());
        }
    } else if (ACTION_REM_HTTP_BREAK_POINT.equals(name)) {
        try {
            extension.removeHttpBreakpoint(params.getString(PARAM_STRING), params.getString(PARAM_LOCATION), params.getString(PARAM_MATCH), params.getBoolean(PARAM_INVERSE), params.getBoolean(PARAM_IGNORECASE));
        } catch (Exception e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, e.getMessage());
        }
    } else {
        throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : Message(org.zaproxy.zap.extension.httppanel.Message) HttpMessage(org.parosproxy.paros.network.HttpMessage) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) HttpMessage(org.parosproxy.paros.network.HttpMessage) ApiException(org.zaproxy.zap.extension.api.ApiException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) ApiException(org.zaproxy.zap.extension.api.ApiException)

Aggregations

HttpMessage (org.parosproxy.paros.network.HttpMessage)205 Test (org.junit.Test)144 Source (net.htmlparser.jericho.Source)73 SpiderParam (org.zaproxy.zap.spider.SpiderParam)29 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)22 DatabaseException (org.parosproxy.paros.db.DatabaseException)19 IOException (java.io.IOException)14 URI (org.apache.commons.httpclient.URI)10 URIException (org.apache.commons.httpclient.URIException)10 HttpException (org.apache.commons.httpclient.HttpException)7 HistoryReference (org.parosproxy.paros.model.HistoryReference)6 HttpRequestHeader (org.parosproxy.paros.network.HttpRequestHeader)6 WithConfigsTest (org.zaproxy.zap.WithConfigsTest)6 DefaultValueGenerator (org.zaproxy.zap.model.DefaultValueGenerator)6 SocketTimeoutException (java.net.SocketTimeoutException)5 RecordHistory (org.parosproxy.paros.db.RecordHistory)4 HttpResponseHeader (org.parosproxy.paros.network.HttpResponseHeader)4 File (java.io.File)3 SocketException (java.net.SocketException)3 UnknownHostException (java.net.UnknownHostException)3