Search in sources :

Example 1 with ApiResponseElement

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

the class AutoUpdateAPI method handleApiView.

@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
    ApiResponse result;
    if (VIEW_LATEST_VERSION_NUMBER.equals(name)) {
        result = new ApiResponseElement(name, this.getLatestVersionNumber());
    } else if (VIEW_IS_LATEST_VERSION.equals(name)) {
        result = new ApiResponseElement(name, Boolean.toString(this.isLatestVersion()));
    } else if (VIEW_INSTALLED_ADDONS.equals(name)) {
        final ApiResponseList resultList = new ApiResponseList(name);
        for (AddOn ao : extension.getInstalledAddOns()) {
            resultList.addItem(addonToSet(ao));
        }
        result = resultList;
    } else if (VIEW_NEW_ADDONS.equals(name)) {
        final ApiResponseList resultList = new ApiResponseList(name);
        for (AddOn ao : extension.getNewAddOns()) {
            resultList.addItem(addonToSet(ao));
        }
        result = resultList;
    } else if (VIEW_UPDATED_ADDONS.equals(name)) {
        final ApiResponseList resultList = new ApiResponseList(name);
        for (AddOn ao : extension.getUpdatedAddOns()) {
            resultList.addItem(addonToSet(ao));
        }
        result = resultList;
    } else if (VIEW_MARKETPLACE_ADDONS.equals(name)) {
        final ApiResponseList resultList = new ApiResponseList(name);
        for (AddOn ao : extension.getMarketplaceAddOns()) {
            resultList.addItem(addonToSet(ao));
        }
        result = resultList;
    } else {
        throw new ApiException(ApiException.Type.BAD_VIEW);
    }
    return result;
}
Also used : AddOn(org.zaproxy.zap.control.AddOn) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) ApiResponse(org.zaproxy.zap.extension.api.ApiResponse) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 2 with ApiResponseElement

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

the class AlertAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    if (ACTION_DELETE_ALERT.equals(name)) {
        int alertId = ApiUtils.getIntParam(params, PARAM_ID);
        extension.deleteAlert(getAlertFromDb(alertId));
    } else if (ACTION_DELETE_ALL_ALERTS.equals(name)) {
        extension.deleteAllAlerts();
    } else if (ACTION_UPDATE_ALERT.equals(name)) {
        int alertId = ApiUtils.getIntParam(params, PARAM_ALERT_ID);
        String alertName = params.getString(PARAM_ALERT_NAME);
        int riskId = getRiskId(params);
        int confidenceId = getConfidenceId(params);
        String desc = params.getString(PARAM_ALERT_DESCRIPTION);
        String param = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_PARAM);
        String attack = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_ATTACK);
        String otherInfo = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_OTHERINFO);
        String solution = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_SOLUTION);
        String refs = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_REFS);
        String evidence = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_EVIDENCE);
        int cweId = getParam(params, PARAM_CWEID, 0);
        int wascId = getParam(params, PARAM_WASCID, 0);
        Alert updatedAlert = getAlertFromDb(alertId);
        updatedAlert.setName(alertName);
        updatedAlert.setRisk(riskId);
        updatedAlert.setConfidence(confidenceId);
        updatedAlert.setDescription(desc);
        updatedAlert.setParam(param);
        updatedAlert.setAttack(attack);
        updatedAlert.setOtherInfo(otherInfo);
        updatedAlert.setSolution(solution);
        updatedAlert.setReference(refs);
        updatedAlert.setEvidence(evidence);
        updatedAlert.setCweId(cweId);
        updatedAlert.setWascId(wascId);
        processAlertUpdate(updatedAlert);
    } else if (ACTION_ADD_ALERT.equals(name)) {
        int messageId = ApiUtils.getIntParam(params, PARAM_MESSAGE_ID);
        String alertName = ApiUtils.getNonEmptyStringParam(params, PARAM_ALERT_NAME);
        int riskId = getRiskId(params);
        int confidenceId = getConfidenceId(params);
        String desc = params.getString(PARAM_ALERT_DESCRIPTION);
        String param = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_PARAM);
        String attack = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_ATTACK);
        String otherInfo = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_OTHERINFO);
        String solution = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_SOLUTION);
        String refs = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_REFS);
        String evidence = ApiUtils.getOptionalStringParam(params, PARAM_ALERT_EVIDENCE);
        int cweId = getParam(params, PARAM_CWEID, 0);
        int wascId = getParam(params, PARAM_WASCID, 0);
        HttpMessage msg = getHttpMessage(messageId);
        Alert newAlert = new Alert(-1, riskId, confidenceId, alertName);
        newAlert.setSource(Alert.Source.MANUAL);
        newAlert.setMessage(msg);
        newAlert.setUri(msg.getRequestHeader().getURI().toString());
        newAlert.setName(alertName);
        newAlert.setRisk(riskId);
        newAlert.setConfidence(confidenceId);
        newAlert.setDescription(desc);
        newAlert.setParam(param);
        newAlert.setAttack(attack);
        newAlert.setOtherInfo(otherInfo);
        newAlert.setSolution(solution);
        newAlert.setReference(refs);
        newAlert.setEvidence(evidence);
        newAlert.setCweId(cweId);
        newAlert.setWascId(wascId);
        extension.alertFound(newAlert, msg.getHistoryRef());
        return new ApiResponseElement(name, Integer.toString(newAlert.getAlertId()));
    } else if (ACTION_UPDATE_ALERTS_CONFIDENCE.equals(name)) {
        int confidenceId = getConfidenceId(params);
        updateAlerts(params, alert -> alert.setConfidence(confidenceId));
    } else if (ACTION_UPDATE_ALERTS_RISK.equals(name)) {
        int riskId = getRiskId(params);
        updateAlerts(params, alert -> alert.setRisk(riskId));
    } else {
        throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : Text(org.w3c.dom.Text) Arrays(java.util.Arrays) XMLStringUtil(org.zaproxy.zap.utils.XMLStringUtil) Enumeration(java.util.Enumeration) HistoryReference(org.parosproxy.paros.model.HistoryReference) Model(org.parosproxy.paros.model.Model) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) ApiUtils(org.zaproxy.zap.utils.ApiUtils) HashMap(java.util.HashMap) ApiImplementor(org.zaproxy.zap.extension.api.ApiImplementor) ArrayList(java.util.ArrayList) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) Vector(java.util.Vector) Alert(org.parosproxy.paros.core.scanner.Alert) TableAlertTag(org.zaproxy.zap.db.TableAlertTag) StringTokenizer(java.util.StringTokenizer) Document(org.w3c.dom.Document) ApiView(org.zaproxy.zap.extension.api.ApiView) Map(java.util.Map) Constant(org.parosproxy.paros.Constant) JSON(net.sf.json.JSON) HttpMessage(org.parosproxy.paros.network.HttpMessage) RecordAlert(org.parosproxy.paros.db.RecordAlert) ApiResponse(org.zaproxy.zap.extension.api.ApiResponse) ApiException(org.zaproxy.zap.extension.api.ApiException) DatabaseException(org.parosproxy.paros.db.DatabaseException) ApiAction(org.zaproxy.zap.extension.api.ApiAction) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) Consumer(java.util.function.Consumer) TableAlert(org.parosproxy.paros.db.TableAlert) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Element(org.w3c.dom.Element) ApiResponseSet(org.zaproxy.zap.extension.api.ApiResponseSet) JSONObject(net.sf.json.JSONObject) LogManager(org.apache.logging.log4j.LogManager) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) Alert(org.parosproxy.paros.core.scanner.Alert) RecordAlert(org.parosproxy.paros.db.RecordAlert) TableAlert(org.parosproxy.paros.db.TableAlert) HttpMessage(org.parosproxy.paros.network.HttpMessage) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 3 with ApiResponseElement

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

the class UsersAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    log.debug("handleApiAction " + name + " " + params.toString());
    User user;
    Context context;
    switch(name) {
        case ACTION_NEW_USER:
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            String userName = ApiUtils.getNonEmptyStringParam(params, PARAM_USER_NAME);
            user = new User(context.getId(), userName);
            user.setAuthenticationCredentials(context.getAuthenticationMethod().createAuthenticationCredentials());
            extension.getContextUserAuthManager(context.getId()).addUser(user);
            context.save();
            return new ApiResponseElement(PARAM_USER_ID, String.valueOf(user.getId()));
        case ACTION_REMOVE_USER:
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            int userId = ApiUtils.getIntParam(params, PARAM_USER_ID);
            boolean deleted = extension.getContextUserAuthManager(context.getId()).removeUserById(userId);
            if (deleted) {
                context.save();
                return ApiResponseElement.OK;
            } else
                return ApiResponseElement.FAIL;
        case ACTION_SET_ENABLED:
            boolean enabled = false;
            try {
                enabled = params.getBoolean(PARAM_ENABLED);
            } catch (JSONException e) {
                throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_ENABLED + " - should be boolean");
            }
            user = getUser(params);
            user.setEnabled(enabled);
            user.getContext().save();
            return ApiResponseElement.OK;
        case ACTION_SET_NAME:
            String nameSN = params.getString(PARAM_USER_NAME);
            if (nameSN == null || nameSN.isEmpty())
                throw new ApiException(Type.MISSING_PARAMETER, PARAM_USER_NAME);
            user = getUser(params);
            user.setName(nameSN);
            user.getContext().save();
            return ApiResponseElement.OK;
        case ACTION_SET_AUTH_CREDENTIALS:
            // Prepare the params
            JSONObject actionParams;
            if (params.has(PARAM_CREDENTIALS_CONFIG_PARAMS))
                actionParams = API.getParams(params.getString(PARAM_CREDENTIALS_CONFIG_PARAMS));
            else
                actionParams = new JSONObject();
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            actionParams.put(PARAM_CONTEXT_ID, context.getId());
            actionParams.put(PARAM_USER_ID, getUserId(params));
            // Run the method
            ApiDynamicActionImplementor a = loadedAuthenticationMethodActions.get(context.getAuthenticationMethod().getType().getUniqueIdentifier());
            a.handleAction(actionParams);
            context.save();
            return ApiResponseElement.OK;
        case ACTION_AUTHENTICATE_AS_USER:
            user = getUser(params);
            int hId1 = user.getAuthenticationState().getLastAuthRequestHistoryId();
            user.authenticate();
            int hId2 = user.getAuthenticationState().getLastAuthRequestHistoryId();
            if (hId2 > hId1) {
                // Not all authentication methods result in an authentication request.
                // In theory we could get a different one if other reqs are being made, but this
                // is probably as safe as we can make it right now
                ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.class);
                if (extHistory != null) {
                    HistoryReference href = extHistory.getHistoryReference(hId2);
                    try {
                        HttpMessage authMsg = href.getHttpMessage();
                        ApiResponseSet<String> responseSet = ApiResponseConversionUtils.httpMessageToSet(hId2, authMsg);
                        responseSet.put("authSuccessful", Boolean.toString(user.getContext().getAuthenticationMethod().evaluateAuthRequest(authMsg, user.getAuthenticationState())));
                        return responseSet;
                    } catch (Exception e) {
                        log.error("Failed to read auth request from db " + hId2, e);
                        throw new ApiException(Type.INTERNAL_ERROR, e);
                    }
                }
            }
            return ApiResponseElement.OK;
        case ACTION_POLL_AS_USER:
            user = getUser(params);
            try {
                HttpMessage msg = user.getContext().getAuthenticationMethod().pollAsUser(user);
                int href = -1;
                if (msg.getHistoryRef() != null) {
                    href = msg.getHistoryRef().getHistoryId();
                }
                ApiResponseSet<String> responseSet = ApiResponseConversionUtils.httpMessageToSet(href, msg);
                responseSet.put("pollSuccessful", Boolean.toString(user.getContext().getAuthenticationMethod().evaluateAuthRequest(msg, user.getAuthenticationState())));
                return responseSet;
            } catch (IllegalArgumentException e) {
                throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_CONTEXT_ID);
            } catch (IOException e) {
                throw new ApiException(Type.INTERNAL_ERROR, e);
            }
        case ACTION_SET_AUTH_STATE:
            user = getUser(params);
            AuthenticationState state = user.getAuthenticationState();
            String lastPollResultStr = this.getParam(params, PARAM_LAST_POLL_RESULT, "");
            if (StringUtils.isNotBlank(lastPollResultStr)) {
                try {
                    state.setLastPollResult(Boolean.parseBoolean(lastPollResultStr));
                } catch (Exception e) {
                    throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_LAST_POLL_RESULT);
                }
            }
            String lastPollTimeStr = this.getParam(params, PARAM_LAST_POLL_TIME_IN_MS, "");
            if (StringUtils.isNotBlank(lastPollTimeStr)) {
                try {
                    long lastPollTime;
                    if (lastPollTimeStr.equals(TIME_NOW)) {
                        lastPollTime = System.currentTimeMillis();
                    } else {
                        lastPollTime = Long.parseLong(lastPollTimeStr);
                    }
                    state.setLastPollTime(lastPollTime);
                } catch (Exception e) {
                    throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_LAST_POLL_TIME_IN_MS);
                }
            }
            int reqsSinceLastPoll = this.getParam(params, PARAM_REQUESTS_SINCE_LAST_POLL, -1);
            if (reqsSinceLastPoll >= 0) {
                state.setRequestsSincePoll(reqsSinceLastPoll);
            }
            return ApiResponseElement.OK;
        case ACTION_SET_COOKIE:
            user = getUser(params);
            if (user.getAuthenticatedSession() == null) {
                user.setAuthenticatedSession(user.getContext().getSessionManagementMethod().createEmptyWebSession());
            }
            String cookiePath = this.getParam(params, PARAM_COOKIE_PATH, "");
            if (cookiePath.isEmpty()) {
                cookiePath = null;
            }
            user.getAuthenticatedSession().getHttpState().addCookie(new Cookie(params.getString(PARAM_COOKIE_DOMAIN), params.getString(PARAM_COOKIE_NAME), params.getString(PARAM_COOKIE_VALUE), cookiePath, // Setting this to a valid date means it never gets
            null, // returned :/
            this.getParam(params, PARAM_COOKIE_SECURE, false)));
            return ApiResponseElement.OK;
        default:
            throw new ApiException(Type.BAD_ACTION);
    }
}
Also used : Context(org.zaproxy.zap.model.Context) ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) Cookie(org.apache.commons.httpclient.Cookie) User(org.zaproxy.zap.users.User) ExtensionHistory(org.parosproxy.paros.extension.history.ExtensionHistory) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) JSONException(net.sf.json.JSONException) ApiException(org.zaproxy.zap.extension.api.ApiException) IOException(java.io.IOException) AuthenticationState(org.zaproxy.zap.users.AuthenticationState) HistoryReference(org.parosproxy.paros.model.HistoryReference) JSONObject(net.sf.json.JSONObject) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) HttpMessage(org.parosproxy.paros.network.HttpMessage) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 4 with ApiResponseElement

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

the class SpiderAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    log.debug("Request for handleApiAction: " + name + " (params: " + params.toString() + ")");
    SpiderScan scan;
    int maxChildren = -1;
    Context context = null;
    switch(name) {
        case ACTION_START_SCAN:
            // The action is to start a new Scan
            String url = ApiUtils.getOptionalStringParam(params, PARAM_URL);
            if (params.containsKey(PARAM_MAX_CHILDREN)) {
                String maxChildrenStr = params.getString(PARAM_MAX_CHILDREN);
                if (maxChildrenStr != null && maxChildrenStr.length() > 0) {
                    try {
                        maxChildren = Integer.parseInt(maxChildrenStr);
                    } catch (NumberFormatException e) {
                        throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_MAX_CHILDREN);
                    }
                }
            }
            if (params.containsKey(PARAM_CONTEXT_NAME)) {
                String contextName = params.getString(PARAM_CONTEXT_NAME);
                if (!contextName.isEmpty()) {
                    context = ApiUtils.getContextByName(contextName);
                }
            }
            int scanId = scanURL(url, null, maxChildren, this.getParam(params, PARAM_RECURSE, true), context, getParam(params, PARAM_SUBTREE_ONLY, false));
            return new ApiResponseElement(name, Integer.toString(scanId));
        case ACTION_START_SCAN_AS_USER:
            // The action is to start a new Scan from the perspective of a user
            String urlUserScan = ApiUtils.getOptionalStringParam(params, PARAM_URL);
            int userID = ApiUtils.getIntParam(params, PARAM_USER_ID);
            ExtensionUserManagement usersExtension = Control.getSingleton().getExtensionLoader().getExtension(ExtensionUserManagement.class);
            if (usersExtension == null) {
                throw new ApiException(Type.NO_IMPLEMENTOR, ExtensionUserManagement.NAME);
            }
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            User user = usersExtension.getContextUserAuthManager(context.getId()).getUserById(userID);
            if (user == null) {
                throw new ApiException(Type.USER_NOT_FOUND, PARAM_USER_ID);
            }
            if (params.containsKey(PARAM_MAX_CHILDREN)) {
                String maxChildrenStr = params.getString(PARAM_MAX_CHILDREN);
                if (maxChildrenStr != null && maxChildrenStr.length() > 0) {
                    try {
                        maxChildren = Integer.parseInt(maxChildrenStr);
                    } catch (NumberFormatException e) {
                        throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_MAX_CHILDREN);
                    }
                }
            }
            scanId = scanURL(urlUserScan, user, maxChildren, this.getParam(params, PARAM_RECURSE, true), context, getParam(params, PARAM_SUBTREE_ONLY, false));
            return new ApiResponseElement(name, Integer.toString(scanId));
        case ACTION_PAUSE_SCAN:
            scan = getSpiderScan(params);
            extension.pauseScan(scan.getScanId());
            break;
        case ACTION_RESUME_SCAN:
            scan = getSpiderScan(params);
            extension.resumeScan(scan.getScanId());
            break;
        case ACTION_STOP_SCAN:
            // The action is to stop a pending scan
            scan = getSpiderScan(params);
            extension.stopScan(scan.getScanId());
            break;
        case ACTION_REMOVE_SCAN:
            // Note that we're removing the scan with this call, not just getting it ;)
            scan = getSpiderScan(params);
            extension.removeScan(scan.getScanId());
            break;
        case ACTION_PAUSE_ALL_SCANS:
            extension.pauseAllScans();
            break;
        case ACTION_RESUME_ALL_SCANS:
            extension.resumeAllScans();
            break;
        case ACTION_STOP_ALL_SCANS:
            extension.stopAllScans();
            break;
        case ACTION_REMOVE_ALL_SCANS:
            extension.removeAllScans();
            break;
        case ACTION_CLEAR_EXCLUDED_FROM_SCAN:
            try {
                Session session = Model.getSingleton().getSession();
                session.setExcludeFromSpiderRegexs(new ArrayList<>());
            } catch (DatabaseException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
            break;
        case ACTION_EXCLUDE_FROM_SCAN:
            String regex = params.getString(PARAM_REGEX);
            try {
                Session session = Model.getSingleton().getSession();
                session.addExcludeFromSpiderRegex(regex);
            } catch (DatabaseException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            } catch (PatternSyntaxException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REGEX);
            }
            break;
        case ACTION_ADD_DOMAIN_ALWAYS_IN_SCOPE:
            try {
                String value = params.getString(PARAM_VALUE);
                DomainAlwaysInScopeMatcher domainAlwaysInScope;
                if (getParam(params, PARAM_IS_REGEX, false)) {
                    domainAlwaysInScope = new DomainAlwaysInScopeMatcher(DomainAlwaysInScopeMatcher.createPattern(value));
                } else {
                    domainAlwaysInScope = new DomainAlwaysInScopeMatcher(value);
                }
                domainAlwaysInScope.setEnabled(getParam(params, PARAM_IS_ENABLED, true));
                List<DomainAlwaysInScopeMatcher> domainsAlwaysInScope = new ArrayList<>(extension.getSpiderParam().getDomainsAlwaysInScope());
                domainsAlwaysInScope.add(domainAlwaysInScope);
                extension.getSpiderParam().setDomainsAlwaysInScope(domainsAlwaysInScope);
            } catch (IllegalArgumentException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_VALUE, e);
            }
            break;
        case ACTION_MODIFY_DOMAIN_ALWAYS_IN_SCOPE:
            try {
                int idx = params.getInt(PARAM_IDX);
                if (idx < 0 || idx >= extension.getSpiderParam().getDomainsAlwaysInScope().size()) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
                }
                DomainAlwaysInScopeMatcher oldDomain = extension.getSpiderParam().getDomainsAlwaysInScope().get(idx);
                String value = getParam(params, PARAM_VALUE, oldDomain.getValue());
                if (value.isEmpty()) {
                    value = oldDomain.getValue();
                }
                DomainAlwaysInScopeMatcher newDomain;
                if (getParam(params, PARAM_IS_REGEX, oldDomain.isRegex())) {
                    newDomain = new DomainAlwaysInScopeMatcher(DomainAlwaysInScopeMatcher.createPattern(value));
                } else {
                    newDomain = new DomainAlwaysInScopeMatcher(value);
                }
                newDomain.setEnabled(getParam(params, PARAM_IS_ENABLED, oldDomain.isEnabled()));
                if (oldDomain.equals(newDomain)) {
                    break;
                }
                List<DomainAlwaysInScopeMatcher> domainsAlwaysInScope = new ArrayList<>(extension.getSpiderParam().getDomainsAlwaysInScope());
                domainsAlwaysInScope.set(idx, newDomain);
                extension.getSpiderParam().setDomainsAlwaysInScope(domainsAlwaysInScope);
            } catch (JSONException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
            } catch (IllegalArgumentException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_VALUE, e);
            }
            break;
        case ACTION_REMOVE_DOMAIN_ALWAYS_IN_SCOPE:
            try {
                int idx = params.getInt(PARAM_IDX);
                if (idx < 0 || idx >= extension.getSpiderParam().getDomainsAlwaysInScope().size()) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
                }
                List<DomainAlwaysInScopeMatcher> domainsAlwaysInScope = new ArrayList<>(extension.getSpiderParam().getDomainsAlwaysInScope());
                domainsAlwaysInScope.remove(idx);
                extension.getSpiderParam().setDomainsAlwaysInScope(domainsAlwaysInScope);
            } catch (JSONException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
            }
            break;
        case ACTION_ENABLE_ALL_DOMAINS_ALWAYS_IN_SCOPE:
            setDomainsAlwaysInScopeEnabled(true);
            break;
        case ACTION_DISABLE_ALL_DOMAINS_ALWAYS_IN_SCOPE:
            setDomainsAlwaysInScopeEnabled(false);
            break;
        default:
            throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : Context(org.zaproxy.zap.model.Context) User(org.zaproxy.zap.users.User) ArrayList(java.util.ArrayList) JSONException(net.sf.json.JSONException) DomainAlwaysInScopeMatcher(org.zaproxy.zap.spider.DomainAlwaysInScopeMatcher) ExtensionUserManagement(org.zaproxy.zap.extension.users.ExtensionUserManagement) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) DatabaseException(org.parosproxy.paros.db.DatabaseException) ApiException(org.zaproxy.zap.extension.api.ApiException) Session(org.parosproxy.paros.model.Session) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 5 with ApiResponseElement

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

the class SpiderAPI method handleApiView.

@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
    ApiResponse result;
    if (VIEW_STATUS.equals(name)) {
        SpiderScan scan = this.getSpiderScan(params);
        int progress = 0;
        if (scan.isStopped()) {
            progress = 100;
        } else {
            progress = scan.getProgress();
        }
        result = new ApiResponseElement(name, Integer.toString(progress));
    } else if (VIEW_RESULTS.equals(name)) {
        result = new ApiResponseList(name);
        SpiderScan scan = this.getSpiderScan(params);
        synchronized (scan.getResults()) {
            for (String s : scan.getResults()) {
                ((ApiResponseList) result).addItem(new ApiResponseElement("url", s));
            }
        }
    } else if (VIEW_FULL_RESULTS.equals(name)) {
        ApiResponseList resultUrls = new ApiResponseList(name);
        SpiderScan scan = this.getSpiderScan(params);
        ApiResponseList resultList = new ApiResponseList("urlsInScope");
        synchronized (scan.getResourcesFound()) {
            for (SpiderResource sr : scan.getResourcesFound()) {
                resultList.addItem(createApiResponseSet(sr, sr.isProcessed(), sr.getReasonNotProcessed()));
            }
        }
        resultUrls.addItem(resultList);
        resultList = new ApiResponseList("urlsOutOfScope");
        synchronized (scan.getResultsOutOfScope()) {
            for (String url : scan.getResultsOutOfScope()) {
                resultList.addItem(new ApiResponseElement("url", url));
            }
        }
        resultUrls.addItem(resultList);
        resultList = new ApiResponseList("urlsIoError");
        synchronized (scan.getResourcesIoErrors()) {
            for (SpiderResource sr : scan.getResourcesIoErrors()) {
                resultList.addItem(createApiResponseSet(sr, sr.isProcessed(), sr.getReasonNotProcessed()));
            }
        }
        resultUrls.addItem(resultList);
        result = resultUrls;
    } else if (VIEW_EXCLUDED_FROM_SCAN.equals(name)) {
        result = new ApiResponseList(name);
        Session session = Model.getSingleton().getSession();
        List<String> regexs = session.getExcludeFromSpiderRegexs();
        for (String regex : regexs) {
            ((ApiResponseList) result).addItem(new ApiResponseElement("regex", regex));
        }
    } else if (VIEW_SCANS.equals(name)) {
        ApiResponseList resultList = new ApiResponseList(name);
        for (SpiderScan spiderScan : extension.getAllScans()) {
            Map<String, String> map = new HashMap<>();
            map.put("id", Integer.toString(spiderScan.getScanId()));
            map.put("progress", Integer.toString(spiderScan.getProgress()));
            map.put("state", spiderScan.getState());
            resultList.addItem(new ApiResponseSet<>("scan", map));
        }
        result = resultList;
    } else if (VIEW_ALL_URLS.equals(name)) {
        ApiResponseList resultUrls = new ApiResponseList(name);
        Set<String> urlSet = new HashSet<>();
        TableHistory tableHistory = extension.getModel().getDb().getTableHistory();
        List<Integer> ids = Collections.emptyList();
        try {
            ids = tableHistory.getHistoryIdsOfHistType(extension.getModel().getSession().getSessionId(), HistoryReference.TYPE_SPIDER, HistoryReference.TYPE_SPIDER_TASK);
        } catch (DatabaseException e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
        String url;
        for (Integer id : ids) {
            try {
                RecordHistory rh = tableHistory.read(id);
                if (rh != null) {
                    url = rh.getHttpMessage().getRequestHeader().getURI().toString();
                    if (urlSet.add(url)) {
                        resultUrls.addItem(new ApiResponseElement("url", url));
                    }
                }
            } catch (HttpMalformedHeaderException | DatabaseException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
        result = resultUrls;
    } else if (VIEW_ADDED_NODES.equals(name)) {
        result = new ApiResponseList(name);
        SpiderScan scan = this.getSpiderScan(params);
        for (String s : scan.getAddedNodesTableModel().getAddedNodes()) {
            ((ApiResponseList) result).addItem(new ApiResponseElement("url", s));
        }
    } else if (VIEW_DOMAINS_ALWAYS_IN_SCOPE.equals(name) || VIEW_OPTION_DOMAINS_ALWAYS_IN_SCOPE.equals(name)) {
        result = domainMatchersToApiResponseList(name, extension.getSpiderParam().getDomainsAlwaysInScope(), false);
    } else if (VIEW_OPTION_DOMAINS_ALWAYS_IN_SCOPE_ENABLED.equals(name)) {
        result = domainMatchersToApiResponseList(name, extension.getSpiderParam().getDomainsAlwaysInScope(), true);
    } else {
        throw new ApiException(ApiException.Type.BAD_VIEW);
    }
    return result;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ApiResponseSet(org.zaproxy.zap.extension.api.ApiResponseSet) HashMap(java.util.HashMap) ApiResponse(org.zaproxy.zap.extension.api.ApiResponse) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) ArrayList(java.util.ArrayList) List(java.util.List) TableHistory(org.parosproxy.paros.db.TableHistory) DatabaseException(org.parosproxy.paros.db.DatabaseException) RecordHistory(org.parosproxy.paros.db.RecordHistory) Session(org.parosproxy.paros.model.Session) ApiException(org.zaproxy.zap.extension.api.ApiException)

Aggregations

ApiResponseElement (org.zaproxy.zap.extension.api.ApiResponseElement)18 ApiException (org.zaproxy.zap.extension.api.ApiException)15 ApiResponseList (org.zaproxy.zap.extension.api.ApiResponseList)13 HashMap (java.util.HashMap)9 ApiResponse (org.zaproxy.zap.extension.api.ApiResponse)8 JSONObject (net.sf.json.JSONObject)5 DatabaseException (org.parosproxy.paros.db.DatabaseException)5 ArrayList (java.util.ArrayList)4 Session (org.parosproxy.paros.model.Session)4 Context (org.zaproxy.zap.model.Context)4 User (org.zaproxy.zap.users.User)4 JSONException (net.sf.json.JSONException)3 HttpMessage (org.parosproxy.paros.network.HttpMessage)3 ApiResponseSet (org.zaproxy.zap.extension.api.ApiResponseSet)3 Enumeration (java.util.Enumeration)2 List (java.util.List)2 Map (java.util.Map)2 PatternSyntaxException (java.util.regex.PatternSyntaxException)2 Alert (org.parosproxy.paros.core.scanner.Alert)2 Plugin (org.parosproxy.paros.core.scanner.Plugin)2