Search in sources :

Example 51 with ApiException

use of org.zaproxy.zap.extension.api.ApiException in project zaproxy by zaproxy.

the class SearchAPI method handleApiView.

@Override
public ApiResponse handleApiView(final String name, JSONObject params) throws ApiException {
    final ApiResponseList result = new ApiResponseList(name);
    ExtensionSearch.Type searchType;
    SearchViewResponseType responseType;
    switch(name) {
        case VIEW_URLS_BY_URL_REGEX:
            searchType = ExtensionSearch.Type.URL;
            responseType = SearchViewResponseType.URL;
            break;
        case VIEW_MESSAGES_BY_URL_REGEX:
            searchType = ExtensionSearch.Type.URL;
            responseType = SearchViewResponseType.MESSAGE;
            break;
        case VIEW_URLS_BY_REQUEST_REGEX:
            searchType = ExtensionSearch.Type.Request;
            responseType = SearchViewResponseType.URL;
            break;
        case VIEW_MESSAGES_BY_REQUEST_REGEX:
            searchType = ExtensionSearch.Type.Request;
            responseType = SearchViewResponseType.MESSAGE;
            break;
        case VIEW_URLS_BY_RESPONSE_REGEX:
            searchType = ExtensionSearch.Type.Response;
            responseType = SearchViewResponseType.URL;
            break;
        case VIEW_MESSAGES_BY_RESPONSE_REGEX:
            searchType = ExtensionSearch.Type.Response;
            responseType = SearchViewResponseType.MESSAGE;
            break;
        case VIEW_URLS_BY_HEADER_REGEX:
            searchType = ExtensionSearch.Type.Header;
            responseType = SearchViewResponseType.URL;
            break;
        case VIEW_MESSAGES_BY_HEADER_REGEX:
            searchType = ExtensionSearch.Type.Header;
            responseType = SearchViewResponseType.MESSAGE;
            break;
        default:
            throw new ApiException(ApiException.Type.BAD_VIEW);
    }
    validateRegex(params);
    try {
        SearchResultsProcessor processor;
        if (SearchViewResponseType.MESSAGE == responseType) {
            processor = new SearchResultsProcessor() {

                @Override
                public void processRecordHistory(RecordHistory recordHistory) {
                    result.addItem(ApiResponseConversionUtils.httpMessageToSet(recordHistory.getHistoryId(), recordHistory.getHistoryType(), recordHistory.getHttpMessage()));
                }
            };
        } else {
            processor = new SearchResultsProcessor() {

                @Override
                public void processRecordHistory(RecordHistory recordHistory) {
                    final HttpMessage msg = recordHistory.getHttpMessage();
                    Map<String, String> map = new HashMap<>();
                    map.put("id", String.valueOf(recordHistory.getHistoryId()));
                    map.put("type", String.valueOf(recordHistory.getHistoryType()));
                    map.put("method", msg.getRequestHeader().getMethod());
                    map.put("url", msg.getRequestHeader().getURI().toString());
                    map.put("code", String.valueOf(msg.getResponseHeader().getStatusCode()));
                    map.put("time", String.valueOf(msg.getTimeElapsedMillis()));
                    result.addItem(new ApiResponseSet<>(name, map));
                }
            };
        }
        search(params, searchType, processor);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
    }
    return result;
}
Also used : HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApiException(org.zaproxy.zap.extension.api.ApiException) DatabaseException(org.parosproxy.paros.db.DatabaseException) ApiResponseSet(org.zaproxy.zap.extension.api.ApiResponseSet) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) HttpMessage(org.parosproxy.paros.network.HttpMessage) RecordHistory(org.parosproxy.paros.db.RecordHistory) HashMap(java.util.HashMap) Map(java.util.Map) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 52 with ApiException

use of org.zaproxy.zap.extension.api.ApiException in project zaproxy by zaproxy.

the class ApiUtils method getOptionalEnumParam.

/**
 * Gets an optional enum param, returning {@code null} if the parameter was not found.
 *
 * @param <E> the type of the enum that will be returned
 * @param params the params
 * @param paramName the param name
 * @param enumType the type of the enum
 * @return the enum, or {@code null}
 * @throws ApiException if the param value does not match any of the possible enum values
 */
public static <E extends Enum<E>> E getOptionalEnumParam(JSONObject params, String paramName, Class<E> enumType) throws ApiException {
    String enumValS = params.optString(paramName, null);
    E enumVal = null;
    if (enumValS != null && !enumValS.isEmpty()) {
        try {
            enumVal = Enum.valueOf(enumType, enumValS);
        } catch (Exception ex) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, paramName + ": " + ex.getLocalizedMessage());
        }
    }
    return enumVal;
}
Also used : ApiException(org.zaproxy.zap.extension.api.ApiException) JSONException(net.sf.json.JSONException) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 53 with ApiException

use of org.zaproxy.zap.extension.api.ApiException in project zaproxy by zaproxy.

the class ManualAuthenticationMethodType method getSetCredentialsForUserApiAction.

@Override
public ApiDynamicActionImplementor getSetCredentialsForUserApiAction() {
    return new ApiDynamicActionImplementor(ACTION_SET_CREDENTIALS, new String[] { PARAM_SESSION_NAME }, null) {

        @Override
        public void handleAction(JSONObject params) throws ApiException {
            Context context = ApiUtils.getContextByParamId(params, UsersAPI.PARAM_CONTEXT_ID);
            int userId = ApiUtils.getIntParam(params, UsersAPI.PARAM_USER_ID);
            // Make sure the type of authentication method is compatible
            if (!isTypeForMethod(context.getAuthenticationMethod())) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, "User's credentials should match authentication method type of the context: " + context.getAuthenticationMethod().getType().getName());
            }
            // NOTE: no need to check if extension is loaded as this method
            // is called only if
            // the Users
            // extension is loaded
            ExtensionUserManagement extensionUserManagement = Control.getSingleton().getExtensionLoader().getExtension(ExtensionUserManagement.class);
            User user = extensionUserManagement.getContextUserAuthManager(context.getId()).getUserById(userId);
            if (user == null) {
                throw new ApiException(Type.USER_NOT_FOUND, UsersAPI.PARAM_USER_ID);
            }
            String sessionName = ApiUtils.getNonEmptyStringParam(params, PARAM_SESSION_NAME);
            // Get the matching session
            ExtensionHttpSessions extensionHttpSessions = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHttpSessions.class);
            if (extensionHttpSessions == null) {
                throw new ApiException(Type.NO_IMPLEMENTOR, "HttpSessions extension is not loaded.");
            }
            List<HttpSession> sessions = extensionHttpSessions.getHttpSessionsForContext(context);
            HttpSession matchedSession = null;
            for (HttpSession session : sessions) {
                if (session.getName().equals(sessionName)) {
                    matchedSession = session;
                    break;
                }
            }
            if (matchedSession == null) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SESSION_NAME);
            }
            // Set the credentials
            ManualAuthenticationCredentials credentials = createAuthenticationCredentials();
            credentials.setSelectedSession(matchedSession);
            user.setAuthenticationCredentials(credentials);
        }
    };
}
Also used : ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) Context(org.zaproxy.zap.model.Context) ExtensionUserManagement(org.zaproxy.zap.extension.users.ExtensionUserManagement) User(org.zaproxy.zap.users.User) JSONObject(net.sf.json.JSONObject) HttpSession(org.zaproxy.zap.extension.httpsessions.HttpSession) ExtensionHttpSessions(org.zaproxy.zap.extension.httpsessions.ExtensionHttpSessions) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 54 with ApiException

use of org.zaproxy.zap.extension.api.ApiException in project zaproxy by zaproxy.

the class AlertAPI method handleApiView.

@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
    ApiResponse result = null;
    if (VIEW_ALERT.equals(name)) {
        TableAlert tableAlert = Model.getSingleton().getDb().getTableAlert();
        TableAlertTag tableAlertTag = Model.getSingleton().getDb().getTableAlertTag();
        RecordAlert recordAlert;
        Map<String, String> alertTags;
        try {
            recordAlert = tableAlert.read(this.getParam(params, PARAM_ID, -1));
            alertTags = tableAlertTag.getTagsByAlertId(this.getParam(params, PARAM_ID, -1));
        } catch (DatabaseException e) {
            logger.error("Failed to read the alert from the session:", e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
        if (recordAlert == null) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
        }
        Alert alert = new Alert(recordAlert);
        alert.setTags(alertTags);
        result = new ApiResponseElement(alertToSet(alert));
    } else if (VIEW_ALERTS.equals(name)) {
        final ApiResponseList resultList = new ApiResponseList(name);
        processAlerts(this.getParam(params, PARAM_BASE_URL, (String) null), this.getParam(params, PARAM_START, -1), this.getParam(params, PARAM_COUNT, -1), getRiskId(params), new Processor<Alert>() {

            @Override
            public void process(Alert alert) {
                resultList.addItem(alertToSet(alert));
            }
        });
        result = resultList;
    } else if (VIEW_NUMBER_OF_ALERTS.equals(name)) {
        CounterProcessor<Alert> counter = new CounterProcessor<>();
        processAlerts(this.getParam(params, PARAM_BASE_URL, (String) null), this.getParam(params, PARAM_START, -1), this.getParam(params, PARAM_COUNT, -1), getRiskId(params), counter);
        result = new ApiResponseElement(name, Integer.toString(counter.getCount()));
    } else if (VIEW_ALERTS_SUMMARY.equals(name)) {
        final int[] riskSummary = { 0, 0, 0, 0 };
        Processor<Alert> counter = new Processor<Alert>() {

            @Override
            public void process(Alert alert) {
                riskSummary[alert.getRisk()]++;
            }
        };
        processAlerts(this.getParam(params, PARAM_BASE_URL, (String) null), -1, -1, NO_RISK_ID, counter);
        Map<String, Object> alertData = new HashMap<>();
        for (int i = 0; i < riskSummary.length; i++) {
            alertData.put(Alert.MSG_RISK[i], riskSummary[i]);
        }
        result = new ApiResponseSet<Object>("risk", alertData) {

            @Override
            public JSON toJSON() {
                JSONObject response = new JSONObject();
                response.put(name, super.toJSON());
                return response;
            }
        };
    } else if (VIEW_ALERTS_BY_RISK.equals(name)) {
        String url = this.getParam(params, PARAM_URL, "");
        boolean recurse = this.getParam(params, PARAM_RECURSE, false);
        ApiResponseList resultList = new ApiResponseList(name);
        result = resultList;
        // 0 (RISK_INFO) -> 3 (RISK_HIGH)
        ApiResponseList[] list = new ApiResponseList[4];
        for (int i = 0; i < list.length; i++) {
            list[i] = new ApiResponseList(Alert.MSG_RISK[i]);
        }
        AlertTreeModel model = extension.getTreeModel();
        AlertNode root = (AlertNode) model.getRoot();
        Enumeration<?> enumAllAlerts = root.children();
        while (enumAllAlerts.hasMoreElements()) {
            AlertNode child = (AlertNode) enumAllAlerts.nextElement();
            Alert alert = child.getUserObject();
            ApiResponseList alertList = filterAlertInstances(child, url, recurse);
            if (alertList.getItems().size() > 0) {
                list[alert.getRisk()].addItem(alertList);
            }
        }
        Arrays.stream(list).forEach(resultList::addItem);
    } else if (VIEW_ALERT_COUNTS_BY_RISK.equals(name)) {
        String url = this.getParam(params, PARAM_URL, "");
        boolean recurse = this.getParam(params, PARAM_RECURSE, false);
        // 0 (RISK_INFO) -> 3 (RISK_HIGH)
        int[] counts = new int[] { 0, 0, 0, 0 };
        AlertTreeModel model = extension.getTreeModel();
        AlertNode root = (AlertNode) model.getRoot();
        Enumeration<?> enumAllAlerts = root.children();
        while (enumAllAlerts.hasMoreElements()) {
            AlertNode child = (AlertNode) enumAllAlerts.nextElement();
            Alert alert = child.getUserObject();
            ApiResponseList alertList = filterAlertInstances(child, url, recurse);
            if (alertList.getItems().size() > 0) {
                counts[alert.getRisk()] += 1;
            }
        }
        Map<String, Integer> map = new HashMap<>();
        map.put(Alert.MSG_RISK[Alert.RISK_HIGH], counts[Alert.RISK_HIGH]);
        map.put(Alert.MSG_RISK[Alert.RISK_MEDIUM], counts[Alert.RISK_MEDIUM]);
        map.put(Alert.MSG_RISK[Alert.RISK_LOW], counts[Alert.RISK_LOW]);
        map.put(Alert.MSG_RISK[Alert.RISK_INFO], counts[Alert.RISK_INFO]);
        result = new ApiResponseSet<>(name, map);
    } else {
        throw new ApiException(ApiException.Type.BAD_VIEW);
    }
    return result;
}
Also used : ApiResponse(org.zaproxy.zap.extension.api.ApiResponse) ApiResponseSet(org.zaproxy.zap.extension.api.ApiResponseSet) TableAlertTag(org.zaproxy.zap.db.TableAlertTag) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) Enumeration(java.util.Enumeration) RecordAlert(org.parosproxy.paros.db.RecordAlert) JSONObject(net.sf.json.JSONObject) TableAlert(org.parosproxy.paros.db.TableAlert) Alert(org.parosproxy.paros.core.scanner.Alert) RecordAlert(org.parosproxy.paros.db.RecordAlert) TableAlert(org.parosproxy.paros.db.TableAlert) DatabaseException(org.parosproxy.paros.db.DatabaseException) HashMap(java.util.HashMap) Map(java.util.Map) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 55 with ApiException

use of org.zaproxy.zap.extension.api.ApiException in project zaproxy by zaproxy.

the class BreakAPI method handleApiView.

@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
    if (VIEW_IS_BREAK_ALL.equals(name)) {
        return new ApiResponseElement(name, Boolean.toString(extension.getBreakpointManagementInterface().isBreakAll()));
    } else if (VIEW_IS_BREAK_REQUEST.equals(name)) {
        return new ApiResponseElement(name, Boolean.toString(extension.getBreakpointManagementInterface().isBreakRequest()));
    } else if (VIEW_IS_BREAK_RESPONSE.equals(name)) {
        return new ApiResponseElement(name, Boolean.toString(extension.getBreakpointManagementInterface().isBreakResponse()));
    } else if (VIEW_HTTP_MESSAGE.equals(name)) {
        Message msg = extension.getBreakpointManagementInterface().getMessage();
        if (msg == null) {
            return new ApiResponseElement(name, "");
        } else if (msg instanceof HttpMessage) {
            HttpMessage httpMsg = (HttpMessage) msg;
            StringBuilder sb = new StringBuilder();
            if (extension.getBreakpointManagementInterface().isRequest()) {
                sb.append(httpMsg.getRequestHeader().toString());
                sb.append(httpMsg.getRequestBody().toString());
            } else {
                sb.append(httpMsg.getResponseHeader().toString());
                sb.append(httpMsg.getResponseBody().toString());
            }
            return new ApiResponseElement(name, sb.toString());
        }
        throw new ApiException(ApiException.Type.BAD_TYPE);
    } else {
        throw new ApiException(ApiException.Type.BAD_VIEW);
    }
}
Also used : Message(org.zaproxy.zap.extension.httppanel.Message) HttpMessage(org.parosproxy.paros.network.HttpMessage) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) HttpMessage(org.parosproxy.paros.network.HttpMessage) ApiException(org.zaproxy.zap.extension.api.ApiException)

Aggregations

ApiException (org.zaproxy.zap.extension.api.ApiException)57 JSONObject (net.sf.json.JSONObject)22 Context (org.zaproxy.zap.model.Context)20 ApiResponseList (org.zaproxy.zap.extension.api.ApiResponseList)16 ApiResponseElement (org.zaproxy.zap.extension.api.ApiResponseElement)15 DatabaseException (org.parosproxy.paros.db.DatabaseException)13 HashMap (java.util.HashMap)12 ApiDynamicActionImplementor (org.zaproxy.zap.extension.api.ApiDynamicActionImplementor)10 ApiResponse (org.zaproxy.zap.extension.api.ApiResponse)9 User (org.zaproxy.zap.users.User)9 ArrayList (java.util.ArrayList)8 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)8 HttpMessage (org.parosproxy.paros.network.HttpMessage)7 JSONException (net.sf.json.JSONException)6 ConfigurationException (org.apache.commons.configuration.ConfigurationException)6 IOException (java.io.IOException)5 PatternSyntaxException (java.util.regex.PatternSyntaxException)5 URIException (org.apache.commons.httpclient.URIException)5 RecordContext (org.parosproxy.paros.db.RecordContext)5 ExtensionUserManagement (org.zaproxy.zap.extension.users.ExtensionUserManagement)5