use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.
the class UsernamePasswordAuthenticationCredentials method getSetCredentialsForUserApiAction.
/**
* Gets the api action for setting a {@link UsernamePasswordAuthenticationCredentials} for an
* User.
*
* @param methodType the method type for which this is called
* @return the sets the credentials for user api action
*/
public static ApiDynamicActionImplementor getSetCredentialsForUserApiAction(final AuthenticationMethodType methodType) {
return new ApiDynamicActionImplementor(ACTION_SET_CREDENTIALS, new String[] { PARAM_USERNAME, PARAM_PASSWORD }, null) {
@Override
public void handleAction(JSONObject params) throws ApiException {
Context context = ApiUtils.getContextByParamId(params, UsersAPI.PARAM_CONTEXT_ID);
int userId = ApiUtils.getIntParam(params, UsersAPI.PARAM_USER_ID);
// Make sure the type of authentication method is compatible
if (!methodType.isTypeForMethod(context.getAuthenticationMethod()))
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, "User's credentials should match authentication method type of the context: " + context.getAuthenticationMethod().getType().getName());
// NOTE: no need to check if extension is loaded as this method is called only if
// the Users
// extension is loaded
ExtensionUserManagement extensionUserManagement = Control.getSingleton().getExtensionLoader().getExtension(ExtensionUserManagement.class);
User user = extensionUserManagement.getContextUserAuthManager(context.getId()).getUserById(userId);
if (user == null)
throw new ApiException(ApiException.Type.USER_NOT_FOUND, UsersAPI.PARAM_USER_ID);
// Build and set the credentials
UsernamePasswordAuthenticationCredentials credentials = new UsernamePasswordAuthenticationCredentials();
credentials.username = ApiUtils.getNonEmptyStringParam(params, PARAM_USERNAME);
credentials.password = params.optString(PARAM_PASSWORD, "");
user.setAuthenticationCredentials(credentials);
}
};
}
use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.
the class ScriptBasedAuthenticationMethodType method getSetMethodForContextApiAction.
@Override
public ApiDynamicActionImplementor getSetMethodForContextApiAction() {
return new ApiDynamicActionImplementor(API_METHOD_NAME, new String[] { PARAM_SCRIPT_NAME }, new String[] { PARAM_SCRIPT_CONFIG_PARAMS }) {
@Override
public void handleAction(JSONObject params) throws ApiException {
Context context = ApiUtils.getContextByParamId(params, AuthenticationAPI.PARAM_CONTEXT_ID);
String scriptName = ApiUtils.getNonEmptyStringParam(params, PARAM_SCRIPT_NAME);
// Prepare the method
ScriptBasedAuthenticationMethod method = createAuthenticationMethod(context.getId());
// Load the script and make sure it exists and follows the required interface
ScriptWrapper script = getScriptsExtension().getScript(scriptName);
if (script == null) {
log.error("Unable to find script while loading Script Based Authentication Method for name: " + scriptName);
throw new ApiException(ApiException.Type.SCRIPT_NOT_FOUND, scriptName);
} else
log.info("Loaded script for API:" + script.getName());
method.script = script;
// Check script interface and make sure we load the credentials parameter names
AuthenticationScript s = getScriptInterfaceV2(script);
if (s == null) {
s = getScriptInterface(script);
}
if (s == null) {
log.error("Unable to load Script Based Authentication method. The script " + script.getName() + " does not properly implement the Authentication Script interface.");
throw new ApiException(ApiException.Type.BAD_SCRIPT_FORMAT, "Does not follow Authentication script interface");
}
try {
if (s instanceof AuthenticationScriptV2) {
AuthenticationScriptV2 sV2 = (AuthenticationScriptV2) s;
method.setLoggedInIndicatorPattern(sV2.getLoggedInIndicator());
method.setLoggedOutIndicatorPattern(sV2.getLoggedOutIndicator());
}
method.credentialsParamNames = s.getCredentialsParamsNames();
// Load config param names + values and make sure all of the required ones
// are there
String[] requiredParams = s.getRequiredParamsNames();
String[] optionalParams = s.getOptionalParamsNames();
if (log.isDebugEnabled()) {
log.debug("Loaded authentication script - required parameters: " + Arrays.toString(requiredParams) + " - optional parameters: " + Arrays.toString(optionalParams));
}
Map<String, String> paramValues = new HashMap<>();
for (String rp : requiredParams) {
// If one of the required parameters is not present, it will throw
// an exception
String val = ApiUtils.getNonEmptyStringParam(params, rp);
paramValues.put(rp, val);
}
for (String op : optionalParams) paramValues.put(op, ApiUtils.getOptionalStringParam(params, op));
method.paramValues = paramValues;
if (log.isDebugEnabled())
log.debug("Loaded authentication script parameters:" + paramValues);
} catch (ApiException e) {
throw e;
} catch (Exception e) {
getScriptsExtension().handleScriptException(script, e);
log.error("Unable to load Script Based Authentication method. The script " + script.getName() + " contains errors.");
throw new ApiException(ApiException.Type.BAD_SCRIPT_FORMAT, e.getMessage());
}
context.setAuthenticationMethod(method);
}
};
}
use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.
the class Session method open.
protected void open(String fileName) throws DatabaseException, IOException, Exception {
// TODO extract into db specific classes??
if (Database.DB_TYPE_HSQLDB.equals(model.getDb().getType())) {
configuration = new ZapXmlConfiguration(new File(fileName));
sessionId = configuration.getLong(SESSION_ID);
sessionName = configuration.getString(SESSION_NAME, "");
sessionDesc = configuration.getString(SESSION_DESC, "");
} else {
this.setSessionId(Long.parseLong(fileName));
}
model.getDb().close(false, isCleanUpRequired());
model.getDb().open(fileName);
this.fileName = fileName;
if (View.isInitialised()) {
// Detach the siteTree model from the Sites tree, to reduce notification changes to the
// UI while loading
View.getSingleton().getSiteTreePanel().getTreeSite().setModel(new SiteMap(null, null));
}
if (!Constant.isLowMemoryOptionSet()) {
SiteNode newRoot = new SiteNode(siteTree, -1, Constant.messages.getString("tab.sites"));
siteTree.setRoot(newRoot);
}
// update history reference
List<Integer> list = model.getDb().getTableHistory().getHistoryIdsOfHistType(getSessionId(), HistoryReference.TYPE_PROXIED, HistoryReference.TYPE_ZAP_USER);
HistoryReference historyRef = null;
discardContexts();
// Load the session urls
this.setExcludeFromProxyRegexs(sessionUrlListToStingList(model.getDb().getTableSessionUrl().getUrlsForType(RecordSessionUrl.TYPE_EXCLUDE_FROM_PROXY)));
this.setExcludeFromScanRegexs(sessionUrlListToStingList(model.getDb().getTableSessionUrl().getUrlsForType(RecordSessionUrl.TYPE_EXCLUDE_FROM_SCAN)));
this.setExcludeFromSpiderRegexs(sessionUrlListToStingList(model.getDb().getTableSessionUrl().getUrlsForType(RecordSessionUrl.TYPE_EXCLUDE_FROM_SPIDER)));
for (int i = 0; i < list.size(); i++) {
// ZAP: Removed unnecessary cast.
int historyId = list.get(i);
try {
historyRef = new HistoryReference(historyId);
if (View.isInitialised()) {
final HistoryReference hRef = historyRef;
final HttpMessage msg = historyRef.getHttpMessage();
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
SiteNode sn = getSiteTree().addPath(hRef, msg);
if (sn != null) {
sn.setIncludedInScope(isIncludedInScope(sn), false);
sn.setExcludedFromScope(isExcludedFromScope(sn), false);
}
}
});
} else {
SiteNode sn = getSiteTree().addPath(historyRef);
if (sn != null) {
sn.setIncludedInScope(this.isIncludedInScope(sn), false);
sn.setExcludedFromScope(this.isExcludedFromScope(sn), false);
}
}
// ZAP: Load alerts from db
historyRef.loadAlerts();
if (i % 100 == 99)
Thread.yield();
} catch (Exception e) {
// ZAP: Log exceptions
log.warn(e.getMessage(), e);
}
}
// update siteTree reference
list = model.getDb().getTableHistory().getHistoryIdsOfHistType(getSessionId(), HistoryReference.TYPE_SPIDER, HistoryReference.TYPE_BRUTE_FORCE, HistoryReference.TYPE_SPIDER_AJAX, HistoryReference.TYPE_SCANNER);
for (int i = 0; i < list.size(); i++) {
// ZAP: Removed unnecessary cast.
int historyId = list.get(i);
try {
historyRef = new HistoryReference(historyId);
if (View.isInitialised()) {
final HistoryReference hRef = historyRef;
final HttpMessage msg = historyRef.getHttpMessage();
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
getSiteTree().addPath(hRef, msg);
}
});
} else {
getSiteTree().addPath(historyRef);
}
historyRef.loadAlerts();
if (i % 100 == 99)
Thread.yield();
} catch (Exception e) {
// ZAP: Log exceptions
log.warn(e.getMessage(), e);
}
}
List<RecordContext> contextData = model.getDb().getTableContext().getAllData();
for (RecordContext data : contextData) {
Context ctx = this.getContext(data.getContextId());
if (ctx == null) {
ctx = new Context(this, data.getContextId());
this.addContext(ctx);
if (nextContextId <= data.getContextId()) {
nextContextId = data.getContextId() + 1;
}
}
switch(data.getType()) {
case RecordContext.TYPE_NAME:
ctx.setName(data.getData());
if (View.isInitialised() && !ctx.getName().equals(String.valueOf(ctx.getId()))) {
View.getSingleton().renameContext(ctx);
}
break;
case RecordContext.TYPE_DESCRIPTION:
ctx.setDescription(data.getData());
break;
case RecordContext.TYPE_INCLUDE:
ctx.addIncludeInContextRegex(data.getData());
break;
case RecordContext.TYPE_EXCLUDE:
ctx.addExcludeFromContextRegex(data.getData());
break;
case RecordContext.TYPE_IN_SCOPE:
ctx.setInScope(Boolean.parseBoolean(data.getData()));
break;
case RecordContext.TYPE_INCLUDE_TECH:
ctx.getTechSet().include(new Tech(data.getData()));
break;
case RecordContext.TYPE_EXCLUDE_TECH:
ctx.getTechSet().exclude(new Tech(data.getData()));
break;
}
}
for (Context ctx : contexts) {
try {
// Set up the URL parameter parser
List<String> strs = this.getContextDataStrings(ctx.getId(), RecordContext.TYPE_URL_PARSER_CLASSNAME);
if (strs.size() == 1) {
Class<?> c = ExtensionFactory.getAddOnLoader().loadClass(strs.get(0));
if (c == null) {
log.error("Failed to load URL parser for context " + ctx.getId() + " : " + strs.get(0));
} else {
ParameterParser parser = (ParameterParser) c.getConstructor().newInstance();
strs = this.getContextDataStrings(ctx.getId(), RecordContext.TYPE_URL_PARSER_CONFIG);
if (strs.size() == 1) {
parser.init(strs.get(0));
}
parser.setContext(ctx);
ctx.setUrlParamParser(parser);
}
}
} catch (Exception e) {
log.error("Failed to load URL parser for context " + ctx.getId(), e);
}
try {
// Set up the URL parameter parser
List<String> strs = this.getContextDataStrings(ctx.getId(), RecordContext.TYPE_POST_PARSER_CLASSNAME);
if (strs.size() == 1) {
Class<?> c = ExtensionFactory.getAddOnLoader().loadClass(strs.get(0));
if (c == null) {
log.error("Failed to load POST parser for context " + ctx.getId() + " : " + strs.get(0));
} else {
ParameterParser parser = (ParameterParser) c.getConstructor().newInstance();
strs = this.getContextDataStrings(ctx.getId(), RecordContext.TYPE_POST_PARSER_CONFIG);
if (strs.size() == 1) {
parser.init(strs.get(0));
}
parser.setContext(ctx);
ctx.setPostParamParser(parser);
}
}
} catch (Exception e) {
log.error("Failed to load POST parser for context " + ctx.getId(), e);
}
try {
// Set up the Data Driven Nodes
List<String> strs = this.getContextDataStrings(ctx.getId(), RecordContext.TYPE_DATA_DRIVEN_NODES);
for (String str : strs) {
ctx.addDataDrivenNodes(new StructuralNodeModifier(str));
}
} catch (Exception e) {
log.error("Failed to load data driven nodes for context " + ctx.getId(), e);
}
ctx.restructureSiteTree();
}
if (View.isInitialised()) {
View.getSingleton().getSiteTreePanel().getTreeSite().setModel(siteTree);
View.getSingleton().getSiteTreePanel().expandRoot();
}
this.refreshScope();
Stats.clearAll();
System.gc();
}
use of org.zaproxy.zap.model.Context 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;
}
use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.
the class ApiUtils method getContextByParamId.
/**
* Gets the {@link Context} whose id is provided as a parameter with the given name. Throws an
* exception accordingly if not found or valid.
*
* @param params the params
* @param contextIdParamName the context id param name
* @return the context
* @throws ApiException the api exception
*/
public static Context getContextByParamId(JSONObject params, String contextIdParamName) throws ApiException {
int contextId = getIntParam(params, contextIdParamName);
Context context = Model.getSingleton().getSession().getContext(contextId);
if (context == null) {
throw new ApiException(Type.CONTEXT_NOT_FOUND, contextIdParamName);
}
return context;
}
Aggregations