Search in sources :

Example 1 with TechSet

use of org.zaproxy.zap.model.TechSet in project zaproxy by zaproxy.

the class ContextAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    log.debug("handleApiAction " + name + " " + params.toString());
    Context context;
    TechSet techSet;
    String[] techNames;
    String filename;
    File f;
    switch(name) {
        case ACTION_EXCLUDE_FROM_CONTEXT_REGEX:
            try {
                addExcludeToContext(getContext(params), params.getString(REGEX_PARAM));
            } catch (IllegalArgumentException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, REGEX_PARAM, e);
            }
            break;
        case ACTION_INCLUDE_IN_CONTEXT_REGEX:
            try {
                addIncludeToContext(getContext(params), params.getString(REGEX_PARAM));
            } catch (IllegalArgumentException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, REGEX_PARAM, e);
            }
            break;
        case ACTION_SET_CONTEXT_REGEXS:
            context = getContext(params);
            JSONArray incRegexs;
            JSONArray excRegexs;
            try {
                incRegexs = JSONArray.fromObject(params.get(INC_REGEXS_PARAM));
                context.setIncludeInContextRegexs(JsonUtil.toStringList(incRegexs));
            } catch (JSONException e1) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, INC_REGEXS_PARAM);
            }
            try {
                excRegexs = JSONArray.fromObject(params.get(EXC_REGEXS_PARAM));
                context.setExcludeFromContextRegexs(JsonUtil.toStringList(excRegexs));
            } catch (Exception e1) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, EXC_REGEXS_PARAM);
            }
            Model.getSingleton().getSession().saveContext(context);
            break;
        case ACTION_SET_CONTEXT_CHECKING_STRATEGY:
            context = getContext(params);
            AuthCheckingStrategy checkingStrategy;
            try {
                checkingStrategy = AuthCheckingStrategy.valueOf(params.getString(PARAM_CHECKING_STRATEGRY));
            } catch (Exception e1) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_CHECKING_STRATEGRY);
            }
            if (AuthCheckingStrategy.POLL_URL.equals(checkingStrategy)) {
                AuthPollFrequencyUnits units;
                try {
                    units = AuthPollFrequencyUnits.valueOf(params.getString(PARAM_POLL_FREQ_UNITS));
                } catch (Exception e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_FREQ_UNITS);
                }
                int freq;
                String pollUrl = params.getString(PARAM_POLL_URL);
                String pollData = params.getString(PARAM_POLL_DATA);
                String pollHeaders = params.getString(PARAM_POLL_HEADERS);
                if (pollUrl == null || pollUrl.isEmpty()) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_URL);
                }
                try {
                    new URI(pollUrl, true);
                } catch (Exception e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_URL);
                }
                try {
                    freq = params.getInt(PARAM_POLL_FREQ);
                } catch (Exception e) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_FREQ);
                }
                if (freq <= 0) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_FREQ);
                }
                context.getAuthenticationMethod().setPollUrl(pollUrl);
                context.getAuthenticationMethod().setPollData(pollData);
                context.getAuthenticationMethod().setPollHeaders(pollHeaders);
                context.getAuthenticationMethod().setPollFrequency(freq);
                context.getAuthenticationMethod().setPollFrequencyUnits(units);
            }
            context.getAuthenticationMethod().setAuthCheckingStrategy(checkingStrategy);
            Model.getSingleton().getSession().saveContext(context);
            break;
        case ACTION_NEW_CONTEXT:
            String contextName = params.getString(CONTEXT_NAME);
            try {
                context = Model.getSingleton().getSession().getNewContext(contextName);
            } catch (IllegalContextNameException e) {
                throw new ApiException(ApiException.Type.ALREADY_EXISTS, contextName, e);
            }
            Model.getSingleton().getSession().saveContext(context);
            return new ApiResponseElement(CONTEXT_ID, String.valueOf(context.getId()));
        case ACTION_REMOVE_CONTEXT:
            context = getContext(params);
            Model.getSingleton().getSession().deleteContext(context);
            break;
        case ACTION_SET_CONTEXT_IN_SCOPE:
            context = getContext(params);
            context.setInScope(params.getBoolean(IN_SCOPE));
            Model.getSingleton().getSession().saveContext(context);
            break;
        case ACTION_IMPORT_CONTEXT:
            filename = params.getString(CONTEXT_FILE_PARAM);
            f = new File(filename);
            if (!f.exists()) {
                // Try relative to the contexts dir
                f = new File(Constant.getContextsDir(), filename);
            }
            if (!f.exists()) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST, f.getAbsolutePath());
            } else {
                try {
                    context = Model.getSingleton().getSession().importContext(f);
                } catch (IllegalContextNameException e) {
                    throw new ApiException(ApiException.Type.BAD_EXTERNAL_DATA, e);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                }
            }
            return new ApiResponseElement(CONTEXT_ID, String.valueOf(context.getId()));
        case ACTION_EXPORT_CONTEXT:
            filename = params.getString(CONTEXT_FILE_PARAM);
            context = getContext(params);
            f = new File(filename);
            if (!f.getAbsolutePath().equals(filename)) {
                // Not an absolute filename, use one relative to the contexts dir
                f = new File(Constant.getContextsDir(), filename);
            }
            if (!f.getParentFile().canWrite()) {
                // Cant write to the parent dir so not looking good
                throw new ApiException(ApiException.Type.NO_ACCESS, f.getAbsolutePath());
            } else {
                try {
                    Model.getSingleton().getSession().exportContext(context, f);
                } catch (Exception e) {
                    throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                }
            }
            break;
        case ACTION_INCLUDE_TECHS:
            context = getContext(params);
            techSet = context.getTechSet();
            techNames = getParam(params, PARAM_TECH_NAMES, "").split(",");
            for (String techName : techNames) {
                techSet.include(getTech(techName));
            }
            context.save();
            break;
        case ACTION_INCLUDE_ALL_TECHS:
            context = getContext(params);
            techSet = new TechSet(Tech.getAll());
            context.setTechSet(techSet);
            context.save();
            break;
        case ACTION_EXCLUDE_TECHS:
            context = getContext(params);
            techSet = context.getTechSet();
            techNames = getParam(params, PARAM_TECH_NAMES, "").split(",");
            for (String techName : techNames) {
                techSet.exclude(getTech(techName));
            }
            context.save();
            break;
        case ACTION_EXCLUDE_ALL_TECHS:
            context = getContext(params);
            techSet = context.getTechSet();
            for (Tech tech : Tech.getAll()) {
                techSet.exclude(tech);
            }
            context.save();
            break;
        default:
            throw new ApiException(Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}
Also used : Context(org.zaproxy.zap.model.Context) TechSet(org.zaproxy.zap.model.TechSet) AuthPollFrequencyUnits(org.zaproxy.zap.authentication.AuthenticationMethod.AuthPollFrequencyUnits) JSONArray(net.sf.json.JSONArray) AuthCheckingStrategy(org.zaproxy.zap.authentication.AuthenticationMethod.AuthCheckingStrategy) JSONException(net.sf.json.JSONException) URI(org.apache.commons.httpclient.URI) JSONException(net.sf.json.JSONException) IllegalContextNameException(org.zaproxy.zap.model.IllegalContextNameException) Tech(org.zaproxy.zap.model.Tech) IllegalContextNameException(org.zaproxy.zap.model.IllegalContextNameException) File(java.io.File)

Example 2 with TechSet

use of org.zaproxy.zap.model.TechSet in project zaproxy by zaproxy.

the class HostProcessUnitTest method shouldSetNonNullTechSet.

@Test
void shouldSetNonNullTechSet() {
    // Given
    TechSet techSet = mock(TechSet.class);
    // When
    hostProcess.setTechSet(techSet);
    // Then
    assertThat(hostProcess.getTechSet(), is(equalTo(techSet)));
}
Also used : TechSet(org.zaproxy.zap.model.TechSet) Test(org.junit.jupiter.api.Test)

Example 3 with TechSet

use of org.zaproxy.zap.model.TechSet in project zaproxy by zaproxy.

the class HostProcessUnitTest method shouldThrowWhenSettingNullTechSet.

@Test
void shouldThrowWhenSettingNullTechSet() {
    // Given
    TechSet techSet = null;
    // When/ Then
    assertThrows(IllegalArgumentException.class, () -> hostProcess.setTechSet(techSet));
}
Also used : TechSet(org.zaproxy.zap.model.TechSet) Test(org.junit.jupiter.api.Test)

Example 4 with TechSet

use of org.zaproxy.zap.model.TechSet in project zaproxy by zaproxy.

the class Session method importContext.

/**
 * Imports a context from the specified (XML) file.
 *
 * @param file the (XML) file that contains the context data
 * @return the imported {@code Context}, already added to the session.
 * @throws ConfigurationException
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws IllegalContextNameException (since 2.6.0) if context's name is not provided or it's
 *     empty or if a context with the same name already exists.
 */
public Context importContext(File file) throws ConfigurationException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    ZapXmlConfiguration config = new ZapXmlConfiguration(file);
    String name = config.getString(Context.CONTEXT_CONFIG_NAME);
    validateContextName(name);
    Context c = createContext(name);
    c.setDescription(config.getString(Context.CONTEXT_CONFIG_DESC));
    c.setInScope(config.getBoolean(Context.CONTEXT_CONFIG_INSCOPE, false));
    for (Object obj : config.getList(Context.CONTEXT_CONFIG_INC_REGEXES)) {
        c.addIncludeInContextRegex(obj.toString());
    }
    for (Object obj : config.getList(Context.CONTEXT_CONFIG_EXC_REGEXES)) {
        c.addExcludeFromContextRegex(obj.toString());
    }
    TechSet techSet = new TechSet();
    for (Object obj : config.getList(Context.CONTEXT_CONFIG_TECH_INCLUDE)) {
        techSet.include(new Tech(obj.toString()));
    }
    for (Object obj : config.getList(Context.CONTEXT_CONFIG_TECH_EXCLUDE)) {
        techSet.exclude(new Tech(obj.toString()));
    }
    c.setTechSet(techSet);
    String urlParserClass = config.getString(Context.CONTEXT_CONFIG_URLPARSER_CLASS);
    if (urlParserClass == null) {
        // Can happen due to a bug in 2.4.0 where is was saved using the wrong name :(
        urlParserClass = config.getString(Context.CONTEXT_CONFIG_URLPARSER);
    }
    if (urlParserClass == null) {
        urlParserClass = StandardParameterParser.class.getCanonicalName();
    }
    Class<?> cl = ExtensionFactory.getAddOnLoader().loadClass(urlParserClass);
    if (cl == null) {
        throw new ConfigurationException("Failed to load URL parser for context " + urlParserClass);
    } else {
        ParameterParser parser = (ParameterParser) cl.getConstructor().newInstance();
        parser.init(config.getString(Context.CONTEXT_CONFIG_URLPARSER_CONFIG));
        parser.setContext(c);
        c.setUrlParamParser(parser);
    }
    String postParserClass = config.getString(Context.CONTEXT_CONFIG_POSTPARSER_CLASS);
    String postParserConfig = config.getString(Context.CONTEXT_CONFIG_POSTPARSER_CONFIG);
    if (postParserClass == null) {
        // Can happen due to a bug in 2.4.0 where is was saved using the wrong name :(
        postParserClass = config.getString(urlParserClass);
        postParserConfig = config.getString(Context.CONTEXT_CONFIG_URLPARSER_CONFIG);
    }
    if (postParserClass == null) {
        postParserClass = StandardParameterParser.class.getCanonicalName();
    }
    cl = ExtensionFactory.getAddOnLoader().loadClass(postParserClass);
    if (cl == null) {
        throw new ConfigurationException("Failed to load POST parser for context " + postParserClass);
    } else {
        ParameterParser parser = (ParameterParser) cl.getConstructor().newInstance();
        parser.init(postParserConfig);
        parser.setContext(c);
        c.setPostParamParser(parser);
    }
    for (Object obj : config.getList(Context.CONTEXT_CONFIG_DATA_DRIVEN_NODES)) {
        c.addDataDrivenNodes(new StructuralNodeModifier(obj.toString()));
    }
    model.importContext(c, config);
    c.restructureSiteTree();
    addContext(c);
    saveContext(c);
    return c;
}
Also used : Context(org.zaproxy.zap.model.Context) RecordContext(org.parosproxy.paros.db.RecordContext) Tech(org.zaproxy.zap.model.Tech) TechSet(org.zaproxy.zap.model.TechSet) StandardParameterParser(org.zaproxy.zap.model.StandardParameterParser) ParameterParser(org.zaproxy.zap.model.ParameterParser) StructuralNodeModifier(org.zaproxy.zap.model.StructuralNodeModifier) ConfigurationException(org.apache.commons.configuration.ConfigurationException) StandardParameterParser(org.zaproxy.zap.model.StandardParameterParser) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration)

Example 5 with TechSet

use of org.zaproxy.zap.model.TechSet in project zaproxy by zaproxy.

the class PassiveScanDataUnitTest method shouldUseTechSetOfFirstMatchedContextIfMessageApplicableToMultiple.

@Test
void shouldUseTechSetOfFirstMatchedContextIfMessageApplicableToMultiple() {
    // Given
    HttpMessage msg = createMessage();
    Context matchCtxOne = mock(Context.class);
    TechSet expectedTechSet = new TechSet(Tech.Db);
    given(matchCtxOne.getTechSet()).willReturn(expectedTechSet);
    Context matchCtxTwo = mock(Context.class);
    given(session.getContextsForUrl(msg.getRequestHeader().getURI().toString())).willReturn(asList(matchCtxOne, matchCtxTwo));
    // When
    PassiveScanData psd = new PassiveScanData(msg);
    // Then
    assertThat(psd.getTechSet(), is(equalTo(expectedTechSet)));
}
Also used : Context(org.zaproxy.zap.model.Context) TechSet(org.zaproxy.zap.model.TechSet) HttpMessage(org.parosproxy.paros.network.HttpMessage) Test(org.junit.jupiter.api.Test) WithConfigsTest(org.zaproxy.zap.WithConfigsTest)

Aggregations

TechSet (org.zaproxy.zap.model.TechSet)10 Test (org.junit.jupiter.api.Test)5 Context (org.zaproxy.zap.model.Context)4 Tech (org.zaproxy.zap.model.Tech)4 File (java.io.File)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Entry (java.util.Map.Entry)1 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)1 TreePath (javax.swing.tree.TreePath)1 JSONArray (net.sf.json.JSONArray)1 JSONException (net.sf.json.JSONException)1 ConfigurationException (org.apache.commons.configuration.ConfigurationException)1 URI (org.apache.commons.httpclient.URI)1 Alert (org.parosproxy.paros.core.scanner.Alert)1 ScannerParam (org.parosproxy.paros.core.scanner.ScannerParam)1 RecordContext (org.parosproxy.paros.db.RecordContext)1 Session (org.parosproxy.paros.model.Session)1 SiteNode (org.parosproxy.paros.model.SiteNode)1 HttpMessage (org.parosproxy.paros.network.HttpMessage)1