Search in sources :

Example 16 with ApiException

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

the class UsernamePasswordAuthenticationCredentials method getSetCredentialsForUserApiAction.

/**
	 * Gets the api action for setting a {@link UsernamePasswordAuthenticationCredentials} for an
	 * User.
	 * 
	 * @param methodType the method type for which this is called
	 * @return the sets the credentials for user api action
	 */
public static ApiDynamicActionImplementor getSetCredentialsForUserApiAction(final AuthenticationMethodType methodType) {
    return new ApiDynamicActionImplementor(ACTION_SET_CREDENTIALS, new String[] { PARAM_USERNAME, PARAM_PASSWORD }, 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 (!methodType.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 = (ExtensionUserManagement) Control.getSingleton().getExtensionLoader().getExtension(ExtensionUserManagement.NAME);
            User user = extensionUserManagement.getContextUserAuthManager(context.getIndex()).getUserById(userId);
            if (user == null)
                throw new ApiException(ApiException.Type.USER_NOT_FOUND, UsersAPI.PARAM_USER_ID);
            // Build and set the credentials
            UsernamePasswordAuthenticationCredentials credentials = new UsernamePasswordAuthenticationCredentials();
            credentials.username = ApiUtils.getNonEmptyStringParam(params, PARAM_USERNAME);
            credentials.password = ApiUtils.getNonEmptyStringParam(params, PARAM_PASSWORD);
            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) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 17 with ApiException

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

the class PassiveScanAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    switch(name) {
        case ACTION_SET_ENABLED:
            boolean enabled = getParam(params, PARAM_ENABLED, false);
            extension.setPassiveScanEnabled(enabled);
            break;
        case ACTION_SET_SCAN_ONLY_IN_SCOPE:
            extension.getPassiveScanParam().setScanOnlyInScope(params.getBoolean(PARAM_ONLY_IN_SCOPE));
            break;
        case ACTION_ENABLE_ALL_SCANNERS:
            extension.setAllPluginPassiveScannersEnabled(true);
            break;
        case ACTION_DISABLE_ALL_SCANNERS:
            extension.setAllPluginPassiveScannersEnabled(false);
            break;
        case ACTION_ENABLE_SCANNERS:
            setPluginPassiveScannersEnabled(params, true);
            break;
        case ACTION_DISABLE_SCANNERS:
            setPluginPassiveScannersEnabled(params, false);
            break;
        case ACTION_SET_SCANNER_ALERT_THRESHOLD:
            String paramId = params.getString(PARAM_ID);
            int pluginId;
            try {
                pluginId = Integer.valueOf(paramId.trim()).intValue();
            } catch (NumberFormatException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_ID);
            }
            if (!extension.hasPluginPassiveScanner(pluginId)) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_ID);
            }
            Plugin.AlertThreshold alertThreshold = getAlertThresholdFromParamAlertThreshold(params);
            extension.setPluginPassiveScannerAlertThreshold(pluginId, alertThreshold);
            break;
        default:
            throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : ApiException(org.zaproxy.zap.extension.api.ApiException) Plugin(org.parosproxy.paros.core.scanner.Plugin)

Example 18 with ApiException

use of org.zaproxy.zap.extension.api.ApiException 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() + ")");
    GenericScanner2 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 = (ExtensionUserManagement) Control.getSingleton().getExtensionLoader().getExtension(ExtensionUserManagement.NAME);
            if (usersExtension == null) {
                throw new ApiException(Type.NO_IMPLEMENTOR, ExtensionUserManagement.NAME);
            }
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            User user = usersExtension.getContextUserAuthManager(context.getIndex()).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);
            if (scan == null) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_ID);
            }
            extension.pauseScan(scan.getScanId());
            break;
        case ACTION_RESUME_SCAN:
            scan = getSpiderScan(params);
            if (scan == null) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_ID);
            }
            extension.resumeScan(scan.getScanId());
            break;
        case ACTION_STOP_SCAN:
            // The action is to stop a pending scan
            scan = getSpiderScan(params);
            if (scan == null) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_ID);
            }
            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);
            if (scan == null) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_ID);
            }
            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<String>());
            } 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) GenericScanner2(org.zaproxy.zap.model.GenericScanner2) 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 19 with ApiException

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

the class SpiderAPI method getSpiderScan.

/**
	 * Returns the specified GenericScanner2 or the last scan available.
	 *
	 * @param params the parameters of the API call
	 * @return the GenericScanner2 with the given scan ID or, if not present, the last scan available
	 * @throws ApiException if there's no scan with the given scan ID
	 * @see #PARAM_SCAN_ID
	 */
private GenericScanner2 getSpiderScan(JSONObject params) throws ApiException {
    GenericScanner2 spiderScan;
    int id = getParam(params, PARAM_SCAN_ID, -1);
    if (id == -1) {
        spiderScan = extension.getLastScan();
    } else {
        spiderScan = extension.getScan(id);
    }
    if (spiderScan == null) {
        throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_ID);
    }
    return spiderScan;
}
Also used : GenericScanner2(org.zaproxy.zap.model.GenericScanner2) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 20 with ApiException

use of org.zaproxy.zap.extension.api.ApiException 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 = (SpiderScan) this.getSpiderScan(params);
        int progress = 0;
        if (scan != null) {
            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 = (SpiderScan) this.getSpiderScan(params);
        if (scan != null) {
            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 = (SpiderScan) this.getSpiderScan(params);
        ApiResponseList resultList = new ApiResponseList("urlsInScope");
        synchronized (scan.getResourcesFound()) {
            for (SpiderResource sr : scan.getResourcesFound()) {
                Map<String, String> map = new HashMap<>();
                map.put("messageId", Integer.toString(sr.getHistoryId()));
                map.put("method", sr.getMethod());
                map.put("url", sr.getUri());
                map.put("statusCode", Integer.toString(sr.getStatusCode()));
                map.put("statusReason", sr.getStatusReason());
                resultList.addItem(new ApiResponseSet<String>("resource", map));
            }
        }
        resultUrls.addItem(resultList);
        resultList = new ApiResponseList("urlsOutOfScope");
        synchronized (scan.getResultsOutOfScope()) {
            for (String url : scan.getResultsOutOfScope()) {
                resultList.addItem(new ApiResponseElement("url", url));
            }
        }
        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 (GenericScanner2 scan : extension.getAllScans()) {
            SpiderScan spiderScan = (SpiderScan) scan;
            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<String>("scan", map));
        }
        result = resultList;
    } else if (VIEW_ALL_URLS.equals(name)) {
        ApiResponseList resultUrls = new ApiResponseList(name);
        Set<String> urlSet = new HashSet<String>();
        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.intValue());
                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_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) GenericScanner2(org.zaproxy.zap.model.GenericScanner2) 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

ApiException (org.zaproxy.zap.extension.api.ApiException)44 Context (org.zaproxy.zap.model.Context)18 ApiResponseElement (org.zaproxy.zap.extension.api.ApiResponseElement)12 ApiResponseList (org.zaproxy.zap.extension.api.ApiResponseList)12 JSONObject (net.sf.json.JSONObject)11 DatabaseException (org.parosproxy.paros.db.DatabaseException)10 User (org.zaproxy.zap.users.User)9 ApiDynamicActionImplementor (org.zaproxy.zap.extension.api.ApiDynamicActionImplementor)8 HashMap (java.util.HashMap)7 PatternSyntaxException (java.util.regex.PatternSyntaxException)6 JSONException (net.sf.json.JSONException)6 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)6 ApiResponse (org.zaproxy.zap.extension.api.ApiResponse)6 GenericScanner2 (org.zaproxy.zap.model.GenericScanner2)6 ArrayList (java.util.ArrayList)5 ConfigurationException (org.apache.commons.configuration.ConfigurationException)5 ExtensionUserManagement (org.zaproxy.zap.extension.users.ExtensionUserManagement)5 URIException (org.apache.commons.httpclient.URIException)4 Plugin (org.parosproxy.paros.core.scanner.Plugin)4 Session (org.parosproxy.paros.model.Session)4