Search in sources :

Example 21 with Session

use of org.parosproxy.paros.model.Session in project zaproxy by zaproxy.

the class ActiveScanAPI method handleApiView.

@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
    ApiResponse result;
    ActiveScan activeScan = null;
    ScanPolicy policy;
    int categoryId;
    switch(name) {
        case VIEW_STATUS:
            activeScan = getActiveScan(params);
            int progress = 0;
            if (activeScan.isStopped()) {
                progress = 100;
            } else {
                progress = activeScan.getProgress();
            }
            result = new ApiResponseElement(name, String.valueOf(progress));
            break;
        case VIEW_SCANS:
            ApiResponseList resultList = new ApiResponseList(name);
            for (ActiveScan scan : controller.getAllScans()) {
                Map<String, String> map = new HashMap<>();
                map.put("id", Integer.toString(scan.getScanId()));
                map.put("progress", Integer.toString(scan.getProgress()));
                map.put("state", scan.getState().name());
                map.put("reqCount", Integer.toString(scan.getTotalRequests()));
                map.put("alertCount", Integer.toString(scan.getAlertsIds().size()));
                map.put("newAlertCount", Integer.toString(scan.getTotalNewAlerts()));
                resultList.addItem(new ApiResponseSet<>("scan", map));
            }
            result = resultList;
            break;
        case VIEW_SCAN_PROGRESS:
            resultList = new ApiResponseList(name);
            activeScan = getActiveScan(params);
            for (HostProcess hp : activeScan.getHostProcesses()) {
                ApiResponseList hpList = new ApiResponseList("HostProcess");
                resultList.addItem(new ApiResponseElement("id", hp.getHostAndPort()));
                for (Plugin plugin : hp.getCompleted()) {
                    long timeTaken = plugin.getTimeFinished().getTime() - plugin.getTimeStarted().getTime();
                    int reqs = hp.getPluginRequestCount(plugin.getId());
                    int alertCount = hp.getPluginStats(plugin.getId()).getAlertCount();
                    hpList.addItem(createPluginProgressEntry(plugin, getStatus(hp, plugin, "Complete"), timeTaken, reqs, alertCount));
                }
                for (Plugin plugin : hp.getRunning()) {
                    int pc = hp.getTestCurrentCount(plugin) * 100 / hp.getTestTotalCount();
                    // enumerated at the beginning.
                    if (pc >= 100) {
                        pc = 99;
                    }
                    long timeTaken = new Date().getTime() - plugin.getTimeStarted().getTime();
                    int reqs = hp.getPluginRequestCount(plugin.getId());
                    int alertCount = hp.getPluginStats(plugin.getId()).getAlertCount();
                    hpList.addItem(createPluginProgressEntry(plugin, pc + "%", timeTaken, reqs, alertCount));
                }
                for (Plugin plugin : hp.getPending()) {
                    hpList.addItem(createPluginProgressEntry(plugin, getStatus(hp, plugin, "Pending"), 0, 0, 0));
                }
                resultList.addItem(hpList);
            }
            result = resultList;
            break;
        case VIEW_MESSAGES_IDS:
            resultList = new ApiResponseList(name);
            activeScan = getActiveScan(params);
            synchronized (activeScan.getMessagesIds()) {
                for (Integer id : activeScan.getMessagesIds()) {
                    resultList.addItem(new ApiResponseElement("id", id.toString()));
                }
            }
            result = resultList;
            break;
        case VIEW_ALERTS_IDS:
            resultList = new ApiResponseList(name);
            activeScan = getActiveScan(params);
            synchronized (activeScan.getAlertsIds()) {
                for (Integer id : activeScan.getAlertsIds()) {
                    resultList.addItem(new ApiResponseElement("id", id.toString()));
                }
            }
            result = resultList;
            break;
        case VIEW_EXCLUDED_FROM_SCAN:
            result = new ApiResponseList(name);
            Session session = Model.getSingleton().getSession();
            List<String> regexs = session.getExcludeFromScanRegexs();
            for (String regex : regexs) {
                ((ApiResponseList) result).addItem(new ApiResponseElement("regex", regex));
            }
            break;
        case VIEW_SCANNERS:
            policy = getScanPolicyFromParams(params);
            List<Plugin> scanners = policy.getPluginFactory().getAllPlugin();
            categoryId = getParam(params, PARAM_CATEGORY_ID, -1);
            if (categoryId != -1 && !hasPolicyWithId(categoryId)) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_CATEGORY_ID);
            }
            resultList = new ApiResponseList(name);
            for (Plugin scanner : scanners) {
                if (categoryId == -1 || categoryId == scanner.getCategory()) {
                    resultList.addItem(new ScannerApiResponse(policy, scanner));
                }
            }
            result = resultList;
            break;
        case VIEW_POLICIES:
            policy = getScanPolicyFromParams(params);
            String[] policies = Category.getAllNames();
            resultList = new ApiResponseList(name);
            for (String pluginName : policies) {
                categoryId = Category.getCategory(pluginName);
                Plugin.AttackStrength attackStrength = getPolicyAttackStrength(policy, categoryId);
                Plugin.AlertThreshold alertThreshold = getPolicyAlertThreshold(policy, categoryId);
                Map<String, String> map = new HashMap<>();
                map.put("id", String.valueOf(categoryId));
                map.put("name", pluginName);
                map.put("attackStrength", attackStrength == null ? "" : String.valueOf(attackStrength));
                map.put("alertThreshold", alertThreshold == null ? "" : String.valueOf(alertThreshold));
                map.put("enabled", String.valueOf(isPolicyEnabled(policy, categoryId)));
                resultList.addItem(new ApiResponseSet<>("policy", map));
            }
            result = resultList;
            break;
        case VIEW_SCAN_POLICY_NAMES:
            resultList = new ApiResponseList(name);
            for (String policyName : controller.getPolicyManager().getAllPolicyNames()) {
                resultList.addItem(new ApiResponseElement("policy", policyName));
            }
            result = resultList;
            break;
        case VIEW_ATTACK_MODE_QUEUE:
            result = new ApiResponseElement(name, String.valueOf(controller.getAttackModeStackSize()));
            break;
        case VIEW_OPTION_EXCLUDED_PARAM_LIST:
        case VIEW_EXCLUDED_PARAMS:
            resultList = new ApiResponseList(name);
            List<ScannerParamFilter> excludedParams = controller.getScannerParam().getExcludedParamList();
            for (int i = 0; i < excludedParams.size(); i++) {
                resultList.addItem(new ExcludedParamApiResponse(excludedParams.get(i), i));
            }
            result = resultList;
            break;
        case VIEW_EXCLUDED_PARAM_TYPES:
            resultList = new ApiResponseList(name);
            for (Entry<Integer, String> type : ScannerParamFilter.getTypes().entrySet()) {
                Map<String, String> typeData = new HashMap<>();
                typeData.put("id", Integer.toString(type.getKey()));
                typeData.put("name", type.getValue());
                resultList.addItem(new ApiResponseSet<>("type", typeData));
            }
            result = resultList;
            break;
        default:
            throw new ApiException(ApiException.Type.BAD_VIEW);
    }
    return result;
}
Also used : AlertThreshold(org.parosproxy.paros.core.scanner.Plugin.AlertThreshold) HashMap(java.util.HashMap) ScannerParamFilter(org.parosproxy.paros.core.scanner.ScannerParamFilter) ApiResponse(org.zaproxy.zap.extension.api.ApiResponse) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) Date(java.util.Date) HostProcess(org.parosproxy.paros.core.scanner.HostProcess) Plugin(org.parosproxy.paros.core.scanner.Plugin) Session(org.parosproxy.paros.model.Session) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 22 with Session

use of org.parosproxy.paros.model.Session in project zaproxy by zaproxy.

the class ActiveScanAPI method handleApiAction.

@SuppressWarnings({ "fallthrough" })
@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    log.debug("handleApiAction " + name + " " + params.toString());
    ScanPolicy policy;
    int policyId;
    User user = null;
    Context context = null;
    try {
        switch(name) {
            case ACTION_SCAN_AS_USER:
                // These are not mandatory parameters on purpose, to keep the same order
                // of the parameters while having PARAM_URL as (now) optional.
                validateParamExists(params, PARAM_CONTEXT_ID);
                validateParamExists(params, PARAM_USER_ID);
                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 = usersExtension.getContextUserAuthManager(context.getId()).getUserById(userID);
                if (user == null) {
                    throw new ApiException(Type.USER_NOT_FOUND, PARAM_USER_ID);
                }
            // $FALL-THROUGH$
            case ACTION_SCAN:
                String url = ApiUtils.getOptionalStringParam(params, PARAM_URL);
                if (context == null && params.has(PARAM_CONTEXT_ID) && !params.getString(PARAM_CONTEXT_ID).isEmpty()) {
                    context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
                }
                boolean scanJustInScope = context != null ? false : this.getParam(params, PARAM_JUST_IN_SCOPE, false);
                String policyName = null;
                policy = null;
                try {
                    policyName = params.getString(PARAM_SCAN_POLICY_NAME);
                } catch (Exception e1) {
                // Ignore
                }
                try {
                    if (policyName != null && policyName.length() > 0) {
                        // Not specified, use the default one
                        log.debug("handleApiAction scan policy =" + policyName);
                        policy = controller.getPolicyManager().getPolicy(policyName);
                    }
                } catch (ConfigurationException e) {
                    throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_POLICY_NAME);
                }
                String method = this.getParam(params, PARAM_METHOD, HttpRequestHeader.GET);
                if (method.trim().length() == 0) {
                    method = HttpRequestHeader.GET;
                }
                if (!Arrays.asList(HttpRequestHeader.METHODS).contains(method)) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_METHOD);
                }
                int scanId = scanURL(url, user, this.getParam(params, PARAM_RECURSE, true), scanJustInScope, method, this.getParam(params, PARAM_POST_DATA, ""), policy, context);
                return new ApiResponseElement(name, Integer.toString(scanId));
            case ACTION_PAUSE_SCAN:
                getActiveScan(params).pauseScan();
                break;
            case ACTION_RESUME_SCAN:
                getActiveScan(params).resumeScan();
                break;
            case ACTION_STOP_SCAN:
                getActiveScan(params).stopScan();
                break;
            case ACTION_REMOVE_SCAN:
                ActiveScan activeScan = controller.removeScan(params.getInt(PARAM_SCAN_ID));
                if (activeScan == null) {
                    throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_SCAN_ID);
                }
                break;
            case ACTION_PAUSE_ALL_SCANS:
                controller.pauseAllScans();
                break;
            case ACTION_RESUME_ALL_SCANS:
                controller.resumeAllScans();
                break;
            case ACTION_STOP_ALL_SCANS:
                controller.stopAllScans();
                break;
            case ACTION_REMOVE_ALL_SCANS:
                controller.removeAllScans();
                break;
            case ACTION_CLEAR_EXCLUDED_FROM_SCAN:
                try {
                    Session session = Model.getSingleton().getSession();
                    session.setExcludeFromScanRegexs(new ArrayList<>());
                } catch (DatabaseException e) {
                    log.error(e.getMessage(), 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.addExcludeFromScanRegexs(regex);
                } catch (DatabaseException e) {
                    log.error(e.getMessage(), 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_ENABLE_ALL_SCANNERS:
                policy = getScanPolicyFromParams(params);
                policy.getPluginFactory().setAllPluginEnabled(true);
                policy.save();
                break;
            case ACTION_DISABLE_ALL_SCANNERS:
                policy = getScanPolicyFromParams(params);
                policy.getPluginFactory().setAllPluginEnabled(false);
                policy.save();
                break;
            case ACTION_ENABLE_SCANNERS:
                policy = getScanPolicyFromParams(params);
                setScannersEnabled(policy, getParam(params, PARAM_IDS, "").split(","), true);
                policy.save();
                break;
            case ACTION_DISABLE_SCANNERS:
                policy = getScanPolicyFromParams(params);
                setScannersEnabled(policy, getParam(params, PARAM_IDS, "").split(","), false);
                policy.save();
                break;
            case ACTION_SET_ENABLED_POLICIES:
                policy = getScanPolicyFromParams(params);
                setEnabledPolicies(policy, getParam(params, PARAM_IDS, "").split(","));
                policy.save();
                break;
            case ACTION_SET_POLICY_ATTACK_STRENGTH:
                policyId = getPolicyIdFromParamId(params);
                policy = getScanPolicyFromParams(params);
                Plugin.AttackStrength attackStrength = getAttackStrengthFromParamAttack(params);
                for (Plugin scanner : policy.getPluginFactory().getAllPlugin()) {
                    if (scanner.getCategory() == policyId) {
                        scanner.setAttackStrength(attackStrength);
                    }
                }
                policy.save();
                break;
            case ACTION_SET_POLICY_ALERT_THRESHOLD:
                policyId = getPolicyIdFromParamId(params);
                policy = getScanPolicyFromParams(params);
                Plugin.AlertThreshold alertThreshold1 = getAlertThresholdFromParamAlertThreshold(params);
                for (Plugin scanner : policy.getPluginFactory().getAllPlugin()) {
                    if (scanner.getCategory() == policyId) {
                        scanner.setAlertThreshold(alertThreshold1);
                    }
                }
                policy.save();
                break;
            case ACTION_SET_SCANNER_ATTACK_STRENGTH:
                policy = getScanPolicyFromParams(params);
                Plugin scanner = getScannerFromParamId(policy, params);
                scanner.setAttackStrength(getAttackStrengthFromParamAttack(params));
                policy.save();
                break;
            case ACTION_SET_SCANNER_ALERT_THRESHOLD:
                policy = getScanPolicyFromParams(params);
                AlertThreshold alertThreshold2 = getAlertThresholdFromParamAlertThreshold(params);
                getScannerFromParamId(policy, params).setAlertThreshold(alertThreshold2);
                policy.save();
                break;
            case ACTION_ADD_SCAN_POLICY:
                String newPolicyName = params.getString(PARAM_SCAN_POLICY_NAME);
                if (controller.getPolicyManager().getAllPolicyNames().contains(newPolicyName)) {
                    throw new ApiException(ApiException.Type.ALREADY_EXISTS, PARAM_SCAN_POLICY_NAME);
                }
                if (!controller.getPolicyManager().isLegalPolicyName(newPolicyName)) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SCAN_POLICY_NAME);
                }
                policy = controller.getPolicyManager().getTemplatePolicy();
                policy.setName(newPolicyName);
                setAlertThreshold(policy, params);
                setAttackStrength(policy, params);
                controller.getPolicyManager().savePolicy(policy);
                break;
            case ACTION_REMOVE_SCAN_POLICY:
                // Check it exists
                policy = getScanPolicyFromParams(params);
                if (controller.getPolicyManager().getAllPolicyNames().size() == 1) {
                    // Dont remove the last one
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, "You are not allowed to remove the last scan policy");
                }
                controller.getPolicyManager().deletePolicy(policy.getName());
                break;
            case ACTION_UPDATE_SCAN_POLICY:
                policy = getScanPolicyFromParams(params);
                if (!isParamsChanged(policy, params)) {
                    break;
                }
                updateAlertThreshold(policy, params);
                updateAttackStrength(policy, params);
                controller.getPolicyManager().savePolicy(policy);
                break;
            case ACTION_IMPORT_SCAN_POLICY:
                File file = new File(params.getString(PARAM_PATH));
                if (!file.exists()) {
                    throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_PATH);
                }
                if (!file.isFile()) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PATH);
                }
                ScanPolicy scanPolicy;
                try {
                    scanPolicy = new ScanPolicy(new ZapXmlConfiguration(file));
                } catch (IllegalArgumentException | ConfigurationException e) {
                    throw new ApiException(ApiException.Type.BAD_EXTERNAL_DATA, file.toString(), e);
                }
                String scanPolicyName = scanPolicy.getName();
                if (scanPolicyName.isEmpty()) {
                    scanPolicyName = file.getName();
                }
                if (controller.getPolicyManager().getAllPolicyNames().contains(scanPolicyName)) {
                    throw new ApiException(ApiException.Type.ALREADY_EXISTS, scanPolicyName);
                }
                if (!controller.getPolicyManager().isLegalPolicyName(scanPolicyName)) {
                    throw new ApiException(ApiException.Type.BAD_EXTERNAL_DATA, scanPolicyName);
                }
                try {
                    controller.getPolicyManager().savePolicy(scanPolicy);
                } catch (ConfigurationException e) {
                    throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
                }
                break;
            case ACTION_ADD_EXCLUDED_PARAM:
                int type = getParam(params, PARAM_TYPE, NameValuePair.TYPE_UNDEFINED);
                if (!ScannerParamFilter.getTypes().containsKey(type)) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_TYPE);
                }
                url = getParam(params, PARAM_URL, "*");
                if (url.isEmpty()) {
                    url = "*";
                }
                ScannerParamFilter excludedParam = new ScannerParamFilter(params.getString(PARAM_NAME), type, url);
                List<ScannerParamFilter> excludedParams = new ArrayList<>(controller.getScannerParam().getExcludedParamList());
                excludedParams.add(excludedParam);
                controller.getScannerParam().setExcludedParamList(excludedParams);
                break;
            case ACTION_MODIFY_EXCLUDED_PARAM:
                try {
                    int idx = params.getInt(PARAM_IDX);
                    if (idx < 0 || idx >= controller.getScannerParam().getExcludedParamList().size()) {
                        throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
                    }
                    ScannerParamFilter oldExcludedParam = controller.getScannerParam().getExcludedParamList().get(idx);
                    String epName = getParam(params, PARAM_NAME, oldExcludedParam.getParamName());
                    if (epName.isEmpty()) {
                        epName = oldExcludedParam.getParamName();
                    }
                    type = getParam(params, PARAM_TYPE, oldExcludedParam.getType());
                    if (!ScannerParamFilter.getTypes().containsKey(type)) {
                        throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_TYPE);
                    }
                    url = getParam(params, PARAM_URL, oldExcludedParam.getWildcardedUrl());
                    if (url.isEmpty()) {
                        url = "*";
                    }
                    ScannerParamFilter newExcludedParam = new ScannerParamFilter(epName, type, url);
                    if (oldExcludedParam.equals(newExcludedParam)) {
                        break;
                    }
                    excludedParams = new ArrayList<>(controller.getScannerParam().getExcludedParamList());
                    excludedParams.set(idx, newExcludedParam);
                    controller.getScannerParam().setExcludedParamList(excludedParams);
                } catch (JSONException e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
                }
                break;
            case ACTION_REMOVE_EXCLUDED_PARAM:
                try {
                    int idx = params.getInt(PARAM_IDX);
                    if (idx < 0 || idx >= controller.getScannerParam().getExcludedParamList().size()) {
                        throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
                    }
                    excludedParams = new ArrayList<>(controller.getScannerParam().getExcludedParamList());
                    excludedParams.remove(idx);
                    controller.getScannerParam().setExcludedParamList(excludedParams);
                } catch (JSONException e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
                }
                break;
            case ACTION_SKIP_SCANNER:
                int pluginId = getParam(params, PARAM_SCANNER_ID, -1);
                if (pluginId == -1) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SCANNER_ID);
                }
                String reason = Constant.messages.getString("ascan.progress.label.skipped.reason.user");
                getActiveScan(params).getHostProcesses().forEach(hp -> hp.pluginSkipped(pluginId, reason));
                break;
            default:
                throw new ApiException(ApiException.Type.BAD_ACTION);
        }
    } catch (ConfigurationException e) {
        throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
    }
    return ApiResponseElement.OK;
}
Also used : AlertThreshold(org.parosproxy.paros.core.scanner.Plugin.AlertThreshold) User(org.zaproxy.zap.users.User) ScannerParamFilter(org.parosproxy.paros.core.scanner.ScannerParamFilter) ArrayList(java.util.ArrayList) ConfigurationException(org.apache.commons.configuration.ConfigurationException) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) PatternSyntaxException(java.util.regex.PatternSyntaxException) Context(org.zaproxy.zap.model.Context) JSONException(net.sf.json.JSONException) URIException(org.apache.commons.httpclient.URIException) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApiException(org.zaproxy.zap.extension.api.ApiException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) JSONException(net.sf.json.JSONException) DatabaseException(org.parosproxy.paros.db.DatabaseException) AlertThreshold(org.parosproxy.paros.core.scanner.Plugin.AlertThreshold) ExtensionUserManagement(org.zaproxy.zap.extension.users.ExtensionUserManagement) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) DatabaseException(org.parosproxy.paros.db.DatabaseException) File(java.io.File) ApiException(org.zaproxy.zap.extension.api.ApiException) Session(org.parosproxy.paros.model.Session) Plugin(org.parosproxy.paros.core.scanner.Plugin)

Example 23 with Session

use of org.parosproxy.paros.model.Session in project zaproxy by zaproxy.

the class CoreAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    Session session = Model.getSingleton().getSession();
    if (ACTION_ACCESS_URL.equals(name)) {
        URI uri;
        try {
            uri = new URI(params.getString(PARAM_URL), true);
        } catch (URIException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
        }
        HttpMessage request;
        try {
            request = new HttpMessage(new HttpRequestHeader(HttpRequestHeader.GET, uri, HttpHeader.HTTP11));
        } catch (HttpMalformedHeaderException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
        }
        return sendHttpMessage(request, getParam(params, PARAM_FOLLOW_REDIRECTS, false), name);
    } else if (ACTION_SHUTDOWN.equals(name)) {
        Thread thread = new Thread("ZAP-Shutdown") {

            @Override
            public void run() {
                try {
                    // Give the API a chance to return
                    sleep(1000);
                } catch (InterruptedException e) {
                // Ignore
                }
                try {
                    Control.getSingleton().shutdown(Model.getSingleton().getOptionsParam().getDatabaseParam().isCompactDatabase());
                    logger.info(Constant.PROGRAM_TITLE + " terminated.");
                } catch (Throwable e) {
                    logger.error("An error occurred while shutting down:", e);
                } finally {
                    System.exit(Control.getSingleton().getExitStatus());
                }
            }
        };
        thread.start();
    } else if (ACTION_SAVE_SESSION.equalsIgnoreCase(name)) {
        // Ignore case for backwards compatibility
        Path sessionPath = SessionUtils.getSessionPath(params.getString(PARAM_SESSION));
        String filename = sessionPath.toAbsolutePath().toString();
        final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);
        if (Files.exists(sessionPath)) {
            boolean sameSession = false;
            if (overwrite && !session.isNewState()) {
                try {
                    sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
                } catch (IOException e) {
                    logger.error("Failed to check if same session path:", e);
                    throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                }
            }
            if (!overwrite || sameSession) {
                throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
            }
        }
        this.savingSession = true;
        try {
            Control.getSingleton().saveSession(filename, this);
        } catch (Exception e) {
            logger.error("Failed to save the session:", e);
            this.savingSession = false;
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
        // Wait for notification that its worked ok
        try {
            while (this.savingSession) {
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            // Probably not an error
            logger.debug(e.getMessage(), e);
        }
        logger.debug("Can now return after saving session");
    } else if (ACTION_SNAPSHOT_SESSION.equalsIgnoreCase(name)) {
        // Ignore case for backwards compatibility
        if (session.isNewState()) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
        }
        List<String> actions = Control.getSingleton().getExtensionLoader().getActiveActions();
        if (!actions.isEmpty()) {
            throw new ApiException(ApiException.Type.BAD_STATE, "Active actions prevent the session snapshot: " + actions);
        }
        String fileName = ApiUtils.getOptionalStringParam(params, PARAM_SESSION);
        if (fileName == null || fileName.isEmpty()) {
            fileName = session.getFileName();
            if (fileName.endsWith(".session")) {
                fileName = fileName.substring(0, fileName.length() - 8);
            }
            fileName += "-" + dateFormat.format(new Date()) + ".session";
        } else {
            Path sessionPath = SessionUtils.getSessionPath(fileName);
            fileName = sessionPath.toAbsolutePath().toString();
            if (Files.exists(sessionPath)) {
                final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);
                boolean sameSession = false;
                try {
                    sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
                } catch (IOException e) {
                    logger.error("Failed to check if same session path:", e);
                    throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                }
                if (!overwrite || sameSession) {
                    throw new ApiException(ApiException.Type.ALREADY_EXISTS, fileName);
                }
            }
        }
        this.savingSession = true;
        try {
            Control.getSingleton().snapshotSession(fileName, this);
        } catch (Exception e) {
            logger.error("Failed to snapshot the session:", e);
            this.savingSession = false;
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
        // Wait for notification that its worked ok
        try {
            while (this.savingSession) {
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            // Probably not an error
            logger.debug(e.getMessage(), e);
        }
        logger.debug("Can now return after saving session");
    } else if (ACTION_LOAD_SESSION.equalsIgnoreCase(name)) {
        // Ignore case for backwards compatibility
        Path sessionPath = SessionUtils.getSessionPath(params.getString(PARAM_SESSION));
        String filename = sessionPath.toAbsolutePath().toString();
        if (!Files.exists(sessionPath)) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, filename);
        }
        try {
            Control.getSingleton().runCommandLineOpenSession(filename);
        } catch (Exception e) {
            logger.error("Failed to load the session:", e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
    } else if (ACTION_NEW_SESSION.equalsIgnoreCase(name)) {
        // Ignore case for backwards compatibility
        String sessionName = null;
        try {
            sessionName = params.getString(PARAM_SESSION);
        } catch (Exception e1) {
        // Ignore
        }
        if (sessionName == null || sessionName.length() == 0) {
            // Create a new 'unnamed' session
            Control.getSingleton().discardSession();
            try {
                Control.getSingleton().newSession();
            } catch (Exception e) {
                logger.error("Failed to create a new session:", e);
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        } else {
            Path sessionPath = SessionUtils.getSessionPath(sessionName);
            String filename = sessionPath.toAbsolutePath().toString();
            final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);
            if (Files.exists(sessionPath) && !overwrite) {
                throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
            }
            try {
                Control.getSingleton().runCommandLineNewSession(filename);
            } catch (Exception e) {
                logger.error("Failed to create a new session:", e);
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
    } else if (ACTION_CLEAR_EXCLUDED_FROM_PROXY.equals(name)) {
        try {
            session.setExcludeFromProxyRegexs(new ArrayList<>());
        } catch (DatabaseException e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
    } else if (ACTION_EXCLUDE_FROM_PROXY.equals(name)) {
        String regex = params.getString(PARAM_REGEX);
        try {
            session.addExcludeFromProxyRegex(regex);
        } catch (DatabaseException e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        } catch (PatternSyntaxException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REGEX);
        }
    } else if (ACTION_SET_HOME_DIRECTORY.equals(name)) {
        File f = new File(params.getString(PARAM_DIR));
        if (f.exists() && f.isDirectory()) {
            Model.getSingleton().getOptionsParam().setUserDirectory(f);
        } else {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_DIR);
        }
    } else if (ACTION_SET_MODE.equals(name)) {
        try {
            Mode mode = Mode.valueOf(params.getString(PARAM_MODE).toLowerCase());
            if (View.isInitialised()) {
                View.getSingleton().getMainFrame().getMainToolbarPanel().setMode(mode);
                View.getSingleton().getMainFrame().getMainMenuBar().setMode(mode);
            } else {
                Control.getSingleton().setMode(mode);
            }
        } catch (Exception e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_MODE);
        }
    } else if (ACTION_GENERATE_ROOT_CA.equals(name)) {
        return getNetworkImplementor().handleApiAction("generateRootCaCert", params);
    } else if (ACTION_SEND_REQUEST.equals(name)) {
        HttpMessage request;
        try {
            request = createRequest(params.getString(PARAM_REQUEST));
        } catch (HttpMalformedHeaderException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REQUEST, e);
        }
        validateForCurrentMode(request);
        return sendHttpMessage(request, getParam(params, PARAM_FOLLOW_REDIRECTS, false), name);
    } else if (ACTION_DELETE_ALL_ALERTS.equals(name)) {
        return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiAction(name, params);
    } else if (ACTION_DELETE_ALERT.equals(name)) {
        return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiAction(name, params);
    } else if (ACTION_COLLECT_GARBAGE.equals(name)) {
        System.gc();
        return ApiResponseElement.OK;
    } else if (ACTION_DELETE_SITE_NODE.equals(name)) {
        try {
            String url = params.getString(PARAM_URL);
            String method = getParam(params, PARAM_METHOD, "GET");
            String postData = getParam(params, PARAM_POST_DATA, "");
            URI uri = new URI(url, true);
            SiteMap siteMap = session.getSiteTree();
            SiteNode siteNode = siteMap.findNode(uri, method, postData);
            if (siteNode == null) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_URL);
            }
            if (getExtHistory() != null) {
                getExtHistory().purge(siteMap, siteNode);
            }
            return ApiResponseElement.OK;
        } catch (URIException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
        }
    } else if (ACTION_ADD_PROXY_CHAIN_EXCLUDED_DOMAIN.equals(name)) {
        try {
            ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
            String value = params.getString(PARAM_VALUE);
            DomainMatcher domain;
            if (getParam(params, PARAM_IS_REGEX, false)) {
                domain = new DomainMatcher(DomainMatcher.createPattern(value));
            } else {
                domain = new DomainMatcher(value);
            }
            domain.setEnabled(getParam(params, PARAM_IS_ENABLED, true));
            List<DomainMatcher> domains = new ArrayList<>(connectionParam.getProxyExcludedDomains());
            domains.add(domain);
            connectionParam.setProxyExcludedDomains(domains);
        } catch (IllegalArgumentException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_VALUE, e);
        }
    } else if (ACTION_MODIFY_PROXY_CHAIN_EXCLUDED_DOMAIN.equals(name)) {
        try {
            ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
            int idx = params.getInt(PARAM_IDX);
            if (idx < 0 || idx >= connectionParam.getProxyExcludedDomains().size()) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
            }
            DomainMatcher oldDomain = connectionParam.getProxyExcludedDomains().get(idx);
            String value = getParam(params, PARAM_VALUE, oldDomain.getValue());
            if (value.isEmpty()) {
                value = oldDomain.getValue();
            }
            DomainMatcher newDomain;
            if (getParam(params, PARAM_IS_REGEX, oldDomain.isRegex())) {
                newDomain = new DomainMatcher(DomainMatcher.createPattern(value));
            } else {
                newDomain = new DomainMatcher(value);
            }
            newDomain.setEnabled(getParam(params, PARAM_IS_ENABLED, oldDomain.isEnabled()));
            if (!oldDomain.equals(newDomain)) {
                List<DomainMatcher> domains = new ArrayList<>(connectionParam.getProxyExcludedDomains());
                domains.set(idx, newDomain);
                connectionParam.setProxyExcludedDomains(domains);
            }
        } 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);
        }
    } else if (ACTION_REMOVE_PROXY_CHAIN_EXCLUDED_DOMAIN.equals(name)) {
        try {
            ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
            int idx = params.getInt(PARAM_IDX);
            if (idx < 0 || idx >= connectionParam.getProxyExcludedDomains().size()) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
            }
            List<DomainMatcher> domains = new ArrayList<>(connectionParam.getProxyExcludedDomains());
            domains.remove(idx);
            connectionParam.setProxyExcludedDomains(domains);
        } catch (JSONException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
        }
    } else if (ACTION_ENABLE_ALL_PROXY_CHAIN_EXCLUDED_DOMAINS.equals(name)) {
        setProxyChainExcludedDomainsEnabled(true);
    } else if (ACTION_DISABLE_ALL_PROXY_CHAIN_EXCLUDED_DOMAINS.equals(name)) {
        setProxyChainExcludedDomainsEnabled(false);
    } else if (ACTION_OPTION_MAXIMUM_ALERT_INSTANCES.equals(name)) {
        try {
            getAlertParam(ApiException.Type.BAD_ACTION).setMaximumInstances(params.getInt(PARAM_NUMBER_OF_INSTANCES));
        } catch (JSONException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_NUMBER_OF_INSTANCES, e);
        }
    } else if (ACTION_OPTION_MERGE_RELATED_ALERTS.equals(name)) {
        try {
            getAlertParam(ApiException.Type.BAD_ACTION).setMergeRelatedIssues(params.getBoolean(PARAM_ENABLED));
        } catch (JSONException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_ENABLED, e);
        }
    } else if (ACTION_OPTION_ALERT_OVERRIDES_FILE_PATH.equals(name)) {
        String filePath = getParam(params, PARAM_FILE_PATH, "");
        if (!filePath.isEmpty()) {
            File file = new File(filePath);
            if (!file.isFile() || !file.canRead()) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE_PATH);
            }
        }
        getAlertParam(ApiException.Type.BAD_ACTION).setOverridesFilename(filePath);
        if (!Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class).reloadOverridesFile()) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE_PATH);
        }
    } else if (ACTION_ENABLE_PKCS12_CLIENT_CERTIFICATE.equals(name)) {
        String filePath = getParam(params, PARAM_FILE_PATH, "");
        if (!filePath.isEmpty()) {
            File file = new File(filePath);
            if (!file.isFile() || !file.canRead()) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE_PATH);
            }
        }
        String password = getParam(params, PARAM_PASSWORD, "");
        if (password.isEmpty()) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PASSWORD);
        }
        int certIndex = getParam(params, PARAM_INDEX, 0);
        if (certIndex < 0) {
            certIndex = 0;
        }
        OptionsParamCertificate certParams = Model.getSingleton().getOptionsParam().getCertificateParam();
        try {
            SSLContextManager contextManager = certParams.getSSLContextManager();
            int ksIndex = contextManager.loadPKCS12Certificate(filePath, password);
            contextManager.unlockKey(ksIndex, certIndex, password);
            contextManager.setDefaultKey(ksIndex, certIndex);
            certParams.setActiveCertificate();
            certParams.setEnableCertificate(true);
            logger.info("Client Certificate enabled from API");
        } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            logger.error("The certificate could not be enabled due to an error", ex);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, ex);
        }
        return ApiResponseElement.OK;
    } else if (ACTION_DISABLE_CLIENT_CERTIFICATE.equals(name)) {
        Model.getSingleton().getOptionsParam().getCertificateParam().setEnableCertificate(false);
        logger.info("Client Certificate disabled from API");
        return ApiResponseElement.OK;
    } else {
        throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : OptionsParamCertificate(org.parosproxy.paros.extension.option.OptionsParamCertificate) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpRequestHeader(org.parosproxy.paros.network.HttpRequestHeader) URI(org.apache.commons.httpclient.URI) KeyManagementException(java.security.KeyManagementException) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) SiteMap(org.parosproxy.paros.model.SiteMap) List(java.util.List) ArrayList(java.util.ArrayList) DomainMatcher(org.zaproxy.zap.network.DomainMatcher) ExtensionAlert(org.zaproxy.zap.extension.alert.ExtensionAlert) PatternSyntaxException(java.util.regex.PatternSyntaxException) SiteNode(org.parosproxy.paros.model.SiteNode) Path(java.nio.file.Path) SSLContextManager(ch.csnc.extension.httpclient.SSLContextManager) Mode(org.parosproxy.paros.control.Control.Mode) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) KeyStoreException(java.security.KeyStoreException) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) PatternSyntaxException(java.util.regex.PatternSyntaxException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) CertificateException(java.security.cert.CertificateException) Date(java.util.Date) ConnectionParam(org.parosproxy.paros.network.ConnectionParam) HttpMessage(org.parosproxy.paros.network.HttpMessage) DatabaseException(org.parosproxy.paros.db.DatabaseException) File(java.io.File) Session(org.parosproxy.paros.model.Session)

Example 24 with Session

use of org.parosproxy.paros.model.Session in project zaproxy by zaproxy.

the class SessionExcludeFromProxyPanel method saveParam.

@Override
public void saveParam(Object obj) throws Exception {
    Session session = (Session) obj;
    session.setExcludeFromProxyRegexs(regexesPanel.getRegexes());
    Model.getSingleton().getOptionsParam().getViewParam().setConfirmRemoveProxyExcludeRegex(!regexesPanel.isRemoveWithoutConfirmation());
}
Also used : Session(org.parosproxy.paros.model.Session)

Example 25 with Session

use of org.parosproxy.paros.model.Session in project zaproxy by zaproxy.

the class SessionExcludeFromSpiderPanel method saveParam.

@Override
public void saveParam(Object obj) throws Exception {
    Session session = (Session) obj;
    session.setExcludeFromSpiderRegexs(regexesPanel.getRegexes());
    Model.getSingleton().getOptionsParam().getViewParam().setConfirmRemoveSpiderExcludeRegex(!regexesPanel.isRemoveWithoutConfirmation());
}
Also used : Session(org.parosproxy.paros.model.Session)

Aggregations

Session (org.parosproxy.paros.model.Session)51 DatabaseException (org.parosproxy.paros.db.DatabaseException)18 Context (org.zaproxy.zap.model.Context)14 ArrayList (java.util.ArrayList)8 JMenuItem (javax.swing.JMenuItem)7 ExtensionPopupMenuItem (org.parosproxy.paros.extension.ExtensionPopupMenuItem)7 File (java.io.File)5 SiteNode (org.parosproxy.paros.model.SiteNode)5 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)5 URIException (org.apache.commons.httpclient.URIException)4 RecordStructure (org.parosproxy.paros.db.RecordStructure)4 HttpMessage (org.parosproxy.paros.network.HttpMessage)4 ApiException (org.zaproxy.zap.extension.api.ApiException)4 ApiResponseElement (org.zaproxy.zap.extension.api.ApiResponseElement)4 Date (java.util.Date)3 HashMap (java.util.HashMap)3 PatternSyntaxException (java.util.regex.PatternSyntaxException)3 JFileChooser (javax.swing.JFileChooser)3 JSONException (net.sf.json.JSONException)3 ExtensionHistory (org.parosproxy.paros.extension.history.ExtensionHistory)3