Search in sources :

Example 36 with DatabaseException

use of org.parosproxy.paros.db.DatabaseException 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);
                if (!context.isIncluded(params.getString(PARAM_URL))) {
                    throw new ApiException(Type.URL_NOT_IN_CONTEXT, PARAM_CONTEXT_ID);
                }
                user = usersExtension.getContextUserAuthManager(context.getIndex()).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:
                GenericScanner2 activeScan = controller.removeScan(Integer.valueOf(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<String>());
                } 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_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;
            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) GenericScanner2(org.zaproxy.zap.model.GenericScanner2) DatabaseException(org.parosproxy.paros.db.DatabaseException) ApiException(org.zaproxy.zap.extension.api.ApiException) Session(org.parosproxy.paros.model.Session) Plugin(org.parosproxy.paros.core.scanner.Plugin)

Example 37 with DatabaseException

use of org.parosproxy.paros.db.DatabaseException in project zaproxy by zaproxy.

the class CoreAPI method handleApiOther.

@Override
public HttpMessage handleApiOther(HttpMessage msg, String name, JSONObject params) throws ApiException {
    if (OTHER_PROXY_PAC.equals(name)) {
        final ProxyParam proxyParam = Model.getSingleton().getOptionsParam().getProxyParam();
        final int port = proxyParam.getProxyPort();
        try {
            String domain = null;
            if (proxyParam.isProxyIpAnyLocalAddress()) {
                String localDomain = msg.getRequestHeader().getHostName();
                if (!API.API_DOMAIN.equals(localDomain)) {
                    domain = localDomain;
                }
            }
            if (domain == null) {
                domain = proxyParam.getProxyIp();
            }
            String response = this.getPacFile(domain, port);
            msg.setResponseHeader(API.getDefaultResponseHeader("text/html", response.length()));
            msg.setResponseBody(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return msg;
    } else if (OTHER_SET_PROXY.equals(name)) {
        /* JSON string:
			 *  {"type":1,
			 *  "http":	{"host":"proxy.corp.com","port":80},
			 *  "ssl":	{"host":"proxy.corp.com","port":80},
			 *  "ftp":{"host":"proxy.corp.com","port":80},
			 *  "socks":{"host":"proxy.corp.com","port":80},
			 *  "shareSettings":true,"socksVersion":5,
			 *  "proxyExcludes":"localhost, 127.0.0.1"}
			 */
        String proxyDetails = params.getString(PARAM_PROXY_DETAILS);
        String response = "OK";
        try {
            try {
                JSONObject json = JSONObject.fromObject(proxyDetails);
                if (json.getInt("type") == 1) {
                    JSONObject httpJson = JSONObject.fromObject(json.get("http"));
                    String proxyHost = httpJson.getString("host");
                    int proxyPort = httpJson.getInt("port");
                    if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
                        Model.getSingleton().getOptionsParam().getConnectionParam().setProxyChainName(proxyHost);
                        Model.getSingleton().getOptionsParam().getConnectionParam().setProxyChainPort(proxyPort);
                    }
                }
            } catch (JSONException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PROXY_DETAILS);
            }
            msg.setResponseHeader(API.getDefaultResponseHeader("text/html", response.length()));
            msg.setResponseBody(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return msg;
    } else if (OTHER_ROOT_CERT.equals(name)) {
        ExtensionDynSSL extDynSSL = (ExtensionDynSSL) Control.getSingleton().getExtensionLoader().getExtension(ExtensionDynSSL.EXTENSION_ID);
        if (extDynSSL != null) {
            try {
                Certificate rootCA = extDynSSL.getRootCA();
                if (rootCA == null) {
                    throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
                }
                final StringWriter sw = new StringWriter();
                try (final PemWriter pw = new PemWriter(sw)) {
                    pw.writeObject(new JcaMiscPEMGenerator(rootCA));
                    pw.flush();
                }
                String response = sw.toString();
                msg.setResponseHeader(API.getDefaultResponseHeader("application/pkix-cert;", response.length()));
                msg.setResponseBody(response);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new ApiException(ApiException.Type.INTERNAL_ERROR);
            }
        } else {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
        }
        return msg;
    } else if (OTHER_XML_REPORT.equals(name)) {
        try {
            writeReportLastScanTo(msg, ScanReportType.XML);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
    } else if (OTHER_HTML_REPORT.equals(name)) {
        try {
            writeReportLastScanTo(msg, ScanReportType.HTML);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
    } else if (OTHER_MD_REPORT.equals(name)) {
        try {
            writeReportLastScanTo(msg, ScanReportType.MD);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
    } else if (OTHER_MESSAGE_HAR.equals(name)) {
        byte[] responseBody;
        try {
            final HarEntries entries = new HarEntries();
            TableHistory tableHistory = Model.getSingleton().getDb().getTableHistory();
            RecordHistory recordHistory;
            try {
                recordHistory = tableHistory.read(this.getParam(params, PARAM_ID, -1));
            } catch (HttpMalformedHeaderException | DatabaseException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR);
            }
            if (recordHistory == null || recordHistory.getHistoryType() == HistoryReference.TYPE_TEMPORARY) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
            }
            entries.addEntry(HarUtils.createHarEntry(recordHistory.getHttpMessage()));
            HarLog harLog = HarUtils.createZapHarLog();
            harLog.setEntries(entries);
            responseBody = HarUtils.harLogToByteArray(harLog);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
        }
        try {
            msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        msg.setResponseBody(responseBody);
        return msg;
    } else if (OTHER_MESSAGES_HAR.equals(name)) {
        byte[] responseBody;
        try {
            final HarEntries entries = new HarEntries();
            processHttpMessages(this.getParam(params, PARAM_BASE_URL, (String) null), this.getParam(params, PARAM_START, -1), this.getParam(params, PARAM_COUNT, -1), new Processor<RecordHistory>() {

                @Override
                public void process(RecordHistory recordHistory) {
                    entries.addEntry(HarUtils.createHarEntry(recordHistory.getHttpMessage()));
                }
            });
            HarLog harLog = HarUtils.createZapHarLog();
            harLog.setEntries(entries);
            responseBody = HarUtils.harLogToByteArray(harLog);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
        }
        try {
            msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        msg.setResponseBody(responseBody);
        return msg;
    } else if (OTHER_SEND_HAR_REQUEST.equals(name)) {
        byte[] responseBody = {};
        HttpMessage request = null;
        try {
            request = HarUtils.createHttpMessage(params.getString(PARAM_REQUEST));
        } catch (IOException e) {
            ApiException apiException = new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REQUEST, e);
            responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
        }
        if (request != null) {
            if (!isValidForCurrentMode(request.getRequestHeader().getURI())) {
                ApiException apiException = new ApiException(ApiException.Type.MODE_VIOLATION);
                responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
            } else {
                boolean followRedirects = getParam(params, PARAM_FOLLOW_REDIRECTS, false);
                try {
                    final HarEntries entries = new HarEntries();
                    sendRequest(request, followRedirects, new Processor<HttpMessage>() {

                        @Override
                        public void process(HttpMessage msg) {
                            entries.addEntry(HarUtils.createHarEntry(msg));
                        }
                    });
                    HarLog harLog = HarUtils.createZapHarLog();
                    harLog.setEntries(entries);
                    responseBody = HarUtils.harLogToByteArray(harLog);
                } catch (ApiException e) {
                    responseBody = e.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                    responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
                }
            }
        }
        try {
            msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        msg.setResponseBody(responseBody);
        return msg;
    } else if (OTHER_SCRIPT_JS.equals(name)) {
        try {
            msg.setResponseBody(API_SCRIPT);
            // Allow caching
            msg.setResponseHeader(API.getDefaultResponseHeader("text/javascript", API_SCRIPT.length(), true));
            msg.getResponseHeader().addHeader(HttpResponseHeader.CACHE_CONTROL, API_SCRIPT_CACHE_CONTROL);
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        return msg;
    } else {
        throw new ApiException(ApiException.Type.BAD_OTHER);
    }
}
Also used : ExtensionDynSSL(org.zaproxy.zap.extension.dynssl.ExtensionDynSSL) JcaMiscPEMGenerator(org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator) StringWriter(java.io.StringWriter) ProxyParam(org.parosproxy.paros.core.proxy.ProxyParam) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) RecordHistory(org.parosproxy.paros.db.RecordHistory) HarEntries(edu.umass.cs.benchlab.har.HarEntries) HarLog(edu.umass.cs.benchlab.har.HarLog) PemWriter(org.bouncycastle.util.io.pem.PemWriter) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) PatternSyntaxException(java.util.regex.PatternSyntaxException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) JSONObject(net.sf.json.JSONObject) TableHistory(org.parosproxy.paros.db.TableHistory) HttpMessage(org.parosproxy.paros.network.HttpMessage) DatabaseException(org.parosproxy.paros.db.DatabaseException) Certificate(java.security.cert.Certificate)

Example 38 with DatabaseException

use of org.parosproxy.paros.db.DatabaseException in project zaproxy by zaproxy.

the class CoreAPI method processAlerts.

private void processAlerts(String baseUrl, int start, int count, Processor<Alert> processor) throws ApiException {
    List<Alert> alerts = new ArrayList<>();
    try {
        TableAlert tableAlert = Model.getSingleton().getDb().getTableAlert();
        // TODO this doesnt work, but should be used when its fixed :/
        //Vector<Integer> v = tableAlert.getAlertListBySession(Model.getSingleton().getSession().getSessionId());
        Vector<Integer> v = tableAlert.getAlertList();
        PaginationConstraintsChecker pcc = new PaginationConstraintsChecker(start, count);
        for (int i = 0; i < v.size(); i++) {
            int alertId = v.get(i).intValue();
            RecordAlert recAlert = tableAlert.read(alertId);
            Alert alert = new Alert(recAlert);
            if (alert.getConfidence() != Alert.CONFIDENCE_FALSE_POSITIVE && !alerts.contains(alert)) {
                if (baseUrl != null && !alert.getUri().startsWith(baseUrl)) {
                    // Not subordinate to the specified URL
                    continue;
                }
                pcc.recordProcessed();
                alerts.add(alert);
                if (!pcc.hasPageStarted()) {
                    continue;
                }
                processor.process(alert);
                if (pcc.hasPageEnded()) {
                    break;
                }
            }
        }
    } catch (DatabaseException e) {
        logger.error(e.getMessage(), e);
        throw new ApiException(ApiException.Type.INTERNAL_ERROR);
    }
}
Also used : TableAlert(org.parosproxy.paros.db.TableAlert) ArrayList(java.util.ArrayList) Alert(org.parosproxy.paros.core.scanner.Alert) RecordAlert(org.parosproxy.paros.db.RecordAlert) ExtensionAlert(org.zaproxy.zap.extension.alert.ExtensionAlert) TableAlert(org.parosproxy.paros.db.TableAlert) DatabaseException(org.parosproxy.paros.db.DatabaseException) RecordAlert(org.parosproxy.paros.db.RecordAlert)

Example 39 with DatabaseException

use of org.parosproxy.paros.db.DatabaseException 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, Model.getSingleton().getOptionsParam().getConnectionParam()));
        } 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() {

            @Override
            public void run() {
                try {
                    // Give the API a chance to return
                    sleep(1000);
                } catch (InterruptedException e) {
                // Ignore
                }
                Control.getSingleton().shutdown(Model.getSingleton().getOptionsParam().getDatabaseParam().isCompactDatabase());
                logger.info(Constant.PROGRAM_TITLE + " terminated.");
                System.exit(0);
            }
        };
        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);
        boolean sameSession = false;
        if (!session.isNewState()) {
            try {
                sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
            } catch (IOException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
        if (Files.exists(sessionPath) && (!overwrite || sameSession)) {
            throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
        }
        this.savingSession = true;
        try {
            Control.getSingleton().saveSession(filename, this);
        } catch (Exception 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);
        }
        String fileName = session.getFileName();
        if (fileName.endsWith(".session")) {
            fileName = fileName.substring(0, fileName.length() - 8);
        }
        fileName += "-" + dateFormat.format(new Date()) + ".session";
        this.savingSession = true;
        try {
            Control.getSingleton().snapshotSession(fileName, this);
        } catch (Exception 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) {
            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) {
                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) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
    } else if (ACTION_CLEAR_EXCLUDED_FROM_PROXY.equals(name)) {
        try {
            session.setExcludeFromProxyRegexs(new ArrayList<String>());
        } 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);
            } 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)) {
        ExtensionDynSSL extDyn = (ExtensionDynSSL) Control.getSingleton().getExtensionLoader().getExtension(ExtensionDynSSL.EXTENSION_ID);
        if (extDyn != null) {
            try {
                extDyn.createNewRootCa();
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
    } 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)) {
        final ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.NAME);
        if (extAlert != null) {
            extAlert.deleteAllAlerts();
        } else {
            try {
                Model.getSingleton().getDb().getTableAlert().deleteAllAlerts();
            } catch (DatabaseException e) {
                logger.error(e.getMessage(), e);
            }
            SiteNode rootNode = (SiteNode) Model.getSingleton().getSession().getSiteTree().getRoot();
            rootNode.deleteAllAlerts();
            removeHistoryReferenceAlerts(rootNode);
        }
    } 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 {
        throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : ArrayList(java.util.ArrayList) ExtensionDynSSL(org.zaproxy.zap.extension.dynssl.ExtensionDynSSL) HttpRequestHeader(org.parosproxy.paros.network.HttpRequestHeader) URI(org.apache.commons.httpclient.URI) 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) Mode(org.parosproxy.paros.control.Control.Mode) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) PatternSyntaxException(java.util.regex.PatternSyntaxException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) 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 40 with DatabaseException

use of org.parosproxy.paros.db.DatabaseException in project zaproxy by zaproxy.

the class ExtensionAntiCSRF method registerAntiCsrfToken.

public void registerAntiCsrfToken(AntiCsrfToken token) {
    log.debug("registerAntiCsrfToken " + token.getMsg().getRequestHeader().getURI().toString() + " " + token.getValue());
    synchronized (valueToToken) {
        try {
            HistoryReference hRef = token.getMsg().getHistoryRef();
            if (hRef == null) {
                hRef = new HistoryReference(getModel().getSession(), HistoryReference.TYPE_TEMPORARY, token.getMsg());
                token.getMsg().setHistoryRef(null);
            }
            token.setHistoryReferenceId(hRef.getHistoryId());
            valueToToken.put(encoder.getURLEncode(token.getValue()), token);
        } catch (HttpMalformedHeaderException | DatabaseException e) {
            log.error("Failed to persist the message: ", e);
        }
    }
}
Also used : HistoryReference(org.parosproxy.paros.model.HistoryReference) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) DatabaseException(org.parosproxy.paros.db.DatabaseException)

Aggregations

DatabaseException (org.parosproxy.paros.db.DatabaseException)153 SQLException (java.sql.SQLException)113 ResultSet (java.sql.ResultSet)61 ArrayList (java.util.ArrayList)28 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)19 PreparedStatement (java.sql.PreparedStatement)11 Session (org.parosproxy.paros.model.Session)11 HttpMessage (org.parosproxy.paros.network.HttpMessage)11 RecordHistory (org.parosproxy.paros.db.RecordHistory)9 RecordAlert (org.parosproxy.paros.db.RecordAlert)7 RecordContext (org.parosproxy.paros.db.RecordContext)7 Vector (java.util.Vector)6 URIException (org.apache.commons.httpclient.URIException)6 IOException (java.io.IOException)5 TableHistory (org.parosproxy.paros.db.TableHistory)5 HistoryReference (org.parosproxy.paros.model.HistoryReference)5 StructuralSiteNode (org.zaproxy.zap.model.StructuralSiteNode)5 Matcher (java.util.regex.Matcher)4 PatternSyntaxException (java.util.regex.PatternSyntaxException)4 JSONException (net.sf.json.JSONException)4