Search in sources :

Example 6 with ConfigurationException

use of org.apache.commons.configuration.ConfigurationException in project gocd by gocd.

the class AgentAutoRegistrationPropertiesImpl method scrubRegistrationProperties.

@Override
public void scrubRegistrationProperties() {
    if (!exist()) {
        return;
    }
    try {
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.setIOFactory(new FilteringOutputWriterFactory());
        PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
        layout.setLineSeparator("\n");
        layout.load(reader());
        try (FileWriter out = new FileWriter(this.configFile)) {
            layout.save(out);
        }
        loadProperties();
    } catch (ConfigurationException | IOException e) {
        LOG.warn("[Agent Auto Registration] Unable to scrub registration key.", e);
    }
}
Also used : ConfigurationException(org.apache.commons.configuration.ConfigurationException) FileWriter(java.io.FileWriter) IOException(java.io.IOException) PropertiesConfiguration(org.apache.commons.configuration.PropertiesConfiguration) PropertiesConfigurationLayout(org.apache.commons.configuration.PropertiesConfigurationLayout)

Example 7 with ConfigurationException

use of org.apache.commons.configuration.ConfigurationException 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 8 with ConfigurationException

use of org.apache.commons.configuration.ConfigurationException in project zaproxy by zaproxy.

the class ExtensionAutoUpdate method getRemoteConfigurationUrl.

private ZapXmlConfiguration getRemoteConfigurationUrl(String url) throws IOException, ConfigurationException, InvalidCfuUrlException {
    HttpMessage msg = new HttpMessage(new URI(url, true), Model.getSingleton().getOptionsParam().getConnectionParam());
    getHttpSender().sendAndReceive(msg, true);
    if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
        throw new IOException();
    }
    if (!msg.getRequestHeader().isSecure()) {
        // Only access the cfu page over https
        throw new InvalidCfuUrlException(msg.getRequestHeader().getURI().toString());
    }
    ZapXmlConfiguration config = new ZapXmlConfiguration();
    config.setDelimiterParsingDisabled(true);
    config.load(new StringReader(msg.getResponseBody().toString()));
    // Save version file so we can report new addons next time
    File f = new File(Constant.FOLDER_LOCAL_PLUGIN, VERSION_FILE_NAME);
    FileWriter out = null;
    try {
        out = new FileWriter(f);
        out.write(msg.getResponseBody().toString());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
        // Ignore
        }
    }
    return config;
}
Also used : FileWriter(java.io.FileWriter) StringReader(java.io.StringReader) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) IOException(java.io.IOException) HttpMessage(org.parosproxy.paros.network.HttpMessage) URI(org.apache.commons.httpclient.URI) File(java.io.File) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException)

Example 9 with ConfigurationException

use of org.apache.commons.configuration.ConfigurationException in project zaproxy by zaproxy.

the class ExtensionAutoUpdate method alertIfNewVersions.

public void alertIfNewVersions() {
    // Kicks off a thread and pops up a window if there are new versions.
    // Depending on the options the user has chosen.
    // Only expect this to be called on startup and in desktop mode
    final OptionsParamCheckForUpdates options = getModel().getOptionsParam().getCheckForUpdatesParam();
    if (View.isInitialised()) {
        if (options.isCheckOnStartUnset()) {
            // First time in
            int result = getView().showConfirmDialog(Constant.messages.getString("cfu.confirm.startCheck"));
            if (result == JOptionPane.OK_OPTION) {
                options.setCheckOnStart(true);
                options.setCheckAddonUpdates(true);
                options.setDownloadNewRelease(true);
            } else {
                options.setCheckOnStart(false);
            }
            // Save
            try {
                this.getModel().getOptionsParam().getConfig().save();
            } catch (ConfigurationException ce) {
                logger.error(ce.getMessage(), ce);
                getView().showWarningDialog(Constant.messages.getString("cfu.confirm.error"));
                return;
            }
        }
        if (!options.isCheckOnStart()) {
            alertIfOutOfDate(false);
            return;
        }
    }
    if (!options.checkOnStart()) {
        // Top level option not set, dont do anything, unless already downloaded last release
        if (View.isInitialised() && this.getPreviousVersionInfo() != null) {
            ZapRelease rel = this.getPreviousVersionInfo().getZapRelease();
            if (rel != null && rel.isNewerThan(this.getCurrentVersion())) {
                File f = new File(Constant.FOLDER_LOCAL_PLUGIN, rel.getFileName());
                if (f.exists() && f.length() >= rel.getSize()) {
                    // Already downloaded, prompt to install and exit
                    this.promptToLaunchReleaseAndClose(rel.getVersion(), f);
                }
            }
        }
        return;
    }
    // Handle the response in a callback
    this.getLatestVersionInfo(this);
}
Also used : ZapRelease(org.zaproxy.zap.control.ZapRelease) ConfigurationException(org.apache.commons.configuration.ConfigurationException) File(java.io.File)

Example 10 with ConfigurationException

use of org.apache.commons.configuration.ConfigurationException in project zaproxy by zaproxy.

the class PolicyManagerDialog method getExportButton.

private JButton getExportButton() {
    if (this.exportButton == null) {
        this.exportButton = new JButton(Constant.messages.getString("ascan.policymgr.button.export"));
        this.exportButton.setEnabled(false);
        this.exportButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String name = (String) getParamsModel().getValueAt(getParamsTable().getSelectedRow(), 0);
                if (name != null) {
                    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
                    File file = new File(Constant.getZapHome(), name + PolicyManager.POLICY_EXTENSION);
                    chooser.setSelectedFile(file);
                    chooser.setFileFilter(new FileFilter() {

                        @Override
                        public boolean accept(File file) {
                            if (file.isDirectory()) {
                                return true;
                            } else if (file.isFile() && file.getName().endsWith(".policy")) {
                                return true;
                            }
                            return false;
                        }

                        @Override
                        public String getDescription() {
                            return Constant.messages.getString("file.format.zap.policy");
                        }
                    });
                    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
                    if (rc == JFileChooser.APPROVE_OPTION) {
                        file = chooser.getSelectedFile();
                        if (file == null) {
                            return;
                        }
                        try {
                            ScanPolicy policy = extension.getPolicyManager().getPolicy(name);
                            if (policy != null) {
                                extension.getPolicyManager().exportPolicy(policy, file);
                            }
                        } catch (ConfigurationException e1) {
                            logger.error(e1.getMessage(), e1);
                            View.getSingleton().showWarningDialog(Constant.messages.getString("ascan.policy.load.error"));
                        }
                    }
                }
            }
        });
    }
    return this.exportButton;
}
Also used : ActionListener(java.awt.event.ActionListener) JFileChooser(javax.swing.JFileChooser) ConfigurationException(org.apache.commons.configuration.ConfigurationException) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) FileFilter(javax.swing.filechooser.FileFilter) File(java.io.File)

Aggregations

ConfigurationException (org.apache.commons.configuration.ConfigurationException)58 PropertiesConfiguration (org.apache.commons.configuration.PropertiesConfiguration)24 File (java.io.File)18 IOException (java.io.IOException)18 ActionEvent (java.awt.event.ActionEvent)6 ActionListener (java.awt.event.ActionListener)5 MalformedURLException (java.net.MalformedURLException)5 ArrayList (java.util.ArrayList)5 ZapXmlConfiguration (org.zaproxy.zap.utils.ZapXmlConfiguration)5 DistributedLogConfiguration (com.twitter.distributedlog.DistributedLogConfiguration)4 FileInputStream (java.io.FileInputStream)4 FileWriter (java.io.FileWriter)4 Configuration (org.apache.commons.configuration.Configuration)4 FileNotFoundException (java.io.FileNotFoundException)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 CommonsConfiguration (com.thinkaurelius.titan.diskstorage.configuration.backend.CommonsConfiguration)2 BufferedWriter (java.io.BufferedWriter)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 SQLException (java.sql.SQLException)2