use of org.parosproxy.paros.model.Model in project zaproxy by zaproxy.
the class SessionStructureUnitTest method setUp.
@BeforeEach
void setUp() throws Exception {
WithConfigsTest.setUpConstantMessages();
factory = new VariantFactory();
model = mock(Model.class);
session = new Session(model);
given(model.getSession()).willReturn(session);
given(model.getVariantFactory()).willReturn(factory);
Control.initSingletonForTesting(model);
msg = new HttpMessage();
}
use of org.parosproxy.paros.model.Model in project zaproxy by zaproxy.
the class ActiveScanAPI method scanURL.
private int scanURL(String url, User user, boolean scanChildren, boolean scanJustInScope, String method, String postData, ScanPolicy policy, Context context) throws ApiException {
boolean useUrl = true;
if (url == null || url.isEmpty()) {
if (context == null || !context.hasNodesInContextFromSiteTree()) {
throw new ApiException(Type.MISSING_PARAMETER, PARAM_URL);
}
useUrl = false;
} else if (context != null && !context.isInContext(url)) {
throw new ApiException(Type.URL_NOT_IN_CONTEXT, PARAM_URL);
}
StructuralNode node = null;
if (useUrl) {
URI startURI;
try {
if (scanChildren && url.endsWith("/")) {
// Always choose the non leaf node if scanChildren option selected
url = url.substring(0, url.length() - 1);
}
startURI = new URI(url, true);
} catch (URIException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
}
String scheme = startURI.getScheme();
if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL + " does not have a scheme.");
}
try {
Model model = Model.getSingleton();
node = SessionStructure.find(model, startURI, method, postData);
if (node == null && "GET".equalsIgnoreCase(method)) {
// Check if there's a non-leaf node that matches the URI, to scan the subtree.
// (GET is the default method, but non-leaf nodes do not have any method.)
node = SessionStructure.find(model, startURI, null, postData);
}
} catch (Exception e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
}
if (node == null) {
throw new ApiException(ApiException.Type.URL_NOT_FOUND);
}
}
Target target;
if (useUrl) {
target = new Target(node);
target.setContext(context);
} else {
target = new Target(context);
}
target.setRecurse(scanChildren);
target.setInScopeOnly(scanJustInScope);
switch(Control.getSingleton().getMode()) {
case safe:
throw new ApiException(ApiException.Type.MODE_VIOLATION);
case protect:
if ((useUrl && !Model.getSingleton().getSession().isInScope(url)) || (context != null && !context.isInScope())) {
throw new ApiException(ApiException.Type.MODE_VIOLATION);
}
// No problem
break;
case standard:
// No problem
break;
case attack:
// No problem
break;
}
Object[] objs = new Object[] {};
if (policy != null) {
objs = new Object[] { policy };
}
return controller.startScan(null, target, user, objs);
}
use of org.parosproxy.paros.model.Model in project zaproxy by zaproxy.
the class CoreAPIUnitTest method setUp.
@BeforeEach
void setUp() {
Model model = mock(Model.class, withSettings().lenient());
Model.setSingletonForTesting(model);
Constant.messages = mock(I18N.class, withSettings().lenient());
networkApi = mock(ApiImplementor.class, withSettings().lenient());
given(networkApi.getPrefix()).willReturn("network");
API.getInstance().registerApiImplementor(networkApi);
coreApi = new CoreAPI(mock(ConnectionParam.class));
}
use of org.parosproxy.paros.model.Model in project zaproxy by zaproxy.
the class CoreAPI method handleApiView.
@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
ApiResponse result = null;
Model model = Model.getSingleton();
Session session = model.getSession();
if (VIEW_HOSTS.equals(name)) {
result = new ApiResponseList(name);
SiteNode root = session.getSiteTree().getRoot();
@SuppressWarnings("unchecked") Enumeration<TreeNode> en = root.children();
while (en.hasMoreElements()) {
String site = ((SiteNode) en.nextElement()).getNodeName();
if (site.indexOf("//") >= 0) {
site = site.substring(site.indexOf("//") + 2);
}
if (site.indexOf(":") >= 0) {
site = site.substring(0, site.indexOf(":"));
}
((ApiResponseList) result).addItem(new ApiResponseElement("host", site));
}
} else if (VIEW_SITES.equals(name)) {
ApiResponseList sitesList = new ApiResponseList(name);
StructuralNode root = SessionStructure.getRootNode(model);
if (root != null) {
for (Iterator<StructuralNode> it = root.getChildIterator(); it.hasNext(); ) {
sitesList.addItem(new ApiResponseElement("site", it.next().getName()));
}
}
result = sitesList;
} else if (VIEW_URLS.equals(name)) {
result = new ApiResponseList(name);
SiteNode root = session.getSiteTree().getRoot();
addUrlsToList(getParam(params, PARAM_BASE_URL, ""), root, new HashSet<>(), (ApiResponseList) result);
} else if (VIEW_CHILD_NODES.equals(name)) {
StructuralNode node;
String url = this.getParam(params, PARAM_URL, "");
if (url.trim().length() == 0) {
node = SessionStructure.getRootNode(model);
} else {
try {
node = SessionStructure.find(Model.getSingleton(), new URI(url, false), null, null);
} catch (URIException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
} catch (DatabaseException e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
}
}
if (node == null) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_URL);
}
result = new ApiResponseList(name);
Iterator<StructuralNode> iter = node.getChildIterator();
while (iter.hasNext()) {
((ApiResponseList) result).addItem(structuralNodeToResponse(iter.next()));
}
} else if (VIEW_ALERT.equals(name)) {
return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiView(name, params);
} else if (VIEW_ALERTS.equals(name)) {
return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiView(name, params);
} else if (VIEW_NUMBER_OF_ALERTS.equals(name)) {
return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiView(name, params);
} else if (VIEW_ALERTS_SUMMARY.equals(name)) {
return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiView(name, params);
} else if (VIEW_MESSAGE.equals(name)) {
TableHistory tableHistory = Model.getSingleton().getDb().getTableHistory();
RecordHistory recordHistory = getRecordHistory(tableHistory, getParam(params, PARAM_ID, -1));
result = new ApiResponseElement(ApiResponseConversionUtils.httpMessageToSet(recordHistory.getHistoryId(), recordHistory.getHistoryType(), recordHistory.getHttpMessage()));
} else if (VIEW_MESSAGES.equals(name)) {
final ApiResponseList resultList = new ApiResponseList(name);
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) {
resultList.addItem(ApiResponseConversionUtils.httpMessageToSet(recordHistory.getHistoryId(), recordHistory.getHistoryType(), recordHistory.getHttpMessage()));
}
});
result = resultList;
} else if (VIEW_NUMBER_OF_MESSAGES.equals(name)) {
CounterProcessor<RecordHistory> counter = new CounterProcessor<>();
processHttpMessages(this.getParam(params, PARAM_BASE_URL, (String) null), this.getParam(params, PARAM_START, -1), this.getParam(params, PARAM_COUNT, -1), counter);
result = new ApiResponseElement(name, Integer.toString(counter.getCount()));
} else if (VIEW_MESSAGES_BY_ID.equals(name)) {
ApiResponseList resultList = new ApiResponseList(name);
TableHistory tableHistory = Model.getSingleton().getDb().getTableHistory();
for (Integer id : getIds(params)) {
RecordHistory recordHistory = getRecordHistory(tableHistory, id);
resultList.addItem(ApiResponseConversionUtils.httpMessageToSet(recordHistory.getHistoryId(), recordHistory.getHistoryType(), recordHistory.getHttpMessage()));
}
result = resultList;
} else if (VIEW_MODE.equals(name)) {
result = new ApiResponseElement(name, Control.getSingleton().getMode().name());
} else if (VIEW_VERSION.equals(name)) {
result = new ApiResponseElement(name, Constant.PROGRAM_VERSION);
} else if (VIEW_EXCLUDED_FROM_PROXY.equals(name)) {
result = new ApiResponseList(name);
List<String> regexs = session.getExcludeFromProxyRegexs();
for (String regex : regexs) {
((ApiResponseList) result).addItem(new ApiResponseElement("regex", regex));
}
} else if (VIEW_HOME_DIRECTORY.equals(name)) {
result = new ApiResponseElement(name, Model.getSingleton().getOptionsParam().getUserDirectory().getAbsolutePath());
} else if (VIEW_SESSION_LOCATION.equals(name)) {
result = new ApiResponseElement(name, session.getFileName());
} else if (VIEW_PROXY_CHAIN_EXCLUDED_DOMAINS.equals(name) || VIEW_OPTION_PROXY_EXCLUDED_DOMAINS.equals(name) || VIEW_OPTION_PROXY_CHAIN_SKIP_NAME.equals(name)) {
result = proxyChainExcludedDomainsToApiResponseList(name, Model.getSingleton().getOptionsParam().getConnectionParam().getProxyExcludedDomains(), false);
} else if (VIEW_OPTION_PROXY_EXCLUDED_DOMAINS_ENABLED.equals(name)) {
result = proxyChainExcludedDomainsToApiResponseList(name, Model.getSingleton().getOptionsParam().getConnectionParam().getProxyExcludedDomains(), true);
} else if (VIEW_ZAP_HOME_PATH.equals(name)) {
result = new ApiResponseElement(name, Constant.getZapHome());
} else if (VIEW_OPTION_MAXIMUM_ALERT_INSTANCES.equals(name)) {
result = new ApiResponseElement(name, String.valueOf(getAlertParam(ApiException.Type.BAD_VIEW).getMaximumInstances()));
} else if (VIEW_OPTION_MERGE_RELATED_ALERTS.equals(name)) {
result = new ApiResponseElement(name, String.valueOf(getAlertParam(ApiException.Type.BAD_VIEW).isMergeRelatedIssues()));
} else if (VIEW_OPTION_ALERT_OVERRIDES_FILE_PATH.equals(name)) {
result = new ApiResponseElement(name, getAlertParam(ApiException.Type.BAD_VIEW).getOverridesFilename());
} else {
throw new ApiException(ApiException.Type.BAD_VIEW);
}
return result;
}
use of org.parosproxy.paros.model.Model in project zaproxy by zaproxy.
the class ExtensionCompare method compareSessions.
private void compareSessions() {
JFileChooser chooser = new JFileChooser(Model.getSingleton().getOptionsParam().getUserDirectory());
File file = null;
chooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (file.isFile() && file.getName().endsWith(".session")) {
return true;
}
return false;
}
@Override
public String getDescription() {
return Constant.messages.getString("file.format.zap.session");
}
});
int rc = chooser.showOpenDialog(getView().getMainFrame());
if (rc == JFileChooser.APPROVE_OPTION) {
try {
file = chooser.getSelectedFile();
if (file == null) {
return;
}
Model cmpModel = new Model();
Session session = cmpModel.getSession();
// log.info("opening session file " + file.getAbsolutePath());
// WaitMessageDialog waitMessageDialog =
// getView().getWaitMessageDialog("Loading session file. Please wait...");
cmpModel.openSession(file, this);
// TODO support other implementations in the future
ParosDatabase db = new ParosDatabase();
db.setDatabaseParam(new DatabaseParam());
db.open(file.getAbsolutePath());
Map<String, String> curMap = new HashMap<>();
Map<String, String> cmpMap = new HashMap<>();
// Load the 2 sessions into 2 maps
this.buildHistoryMap(Model.getSingleton().getDb().getTableHistory(), curMap);
this.buildHistoryMap(db.getTableHistory(), cmpMap);
File outputFile = this.getOutputFile();
if (outputFile != null) {
// Write the result to the specified file
try {
TreeSet<String> sset = new TreeSet<>();
// Combine the keys for both maps
sset.addAll(curMap.keySet());
sset.addAll(cmpMap.keySet());
StringBuilder sb = new StringBuilder(500);
sb.append("<?xml version=\"1.0\"?>");
sb.append(CRLF);
sb.append("<report>");
sb.append(CRLF);
sb.append("<session-names>");
sb.append(CRLF);
sb.append("<session1>");
sb.append(Model.getSingleton().getSession().getSessionName());
sb.append("</session1>");
sb.append(CRLF);
sb.append("<session2>");
sb.append(session.getSessionName());
sb.append("</session2>");
sb.append(CRLF);
sb.append("</session-names>");
sb.append(CRLF);
Iterator<String> iter = sset.iterator();
while (iter.hasNext()) {
sb.append("<urlrow>");
sb.append(CRLF);
String key = iter.next();
String method = key.substring(0, key.indexOf(" "));
String url = key.substring(key.indexOf(" ") + 1);
sb.append("<method>");
sb.append(method);
sb.append("</method>");
sb.append(CRLF);
sb.append("<url>");
sb.append(url);
sb.append("</url>");
sb.append(CRLF);
sb.append("<code1>");
if (curMap.containsKey(key)) {
sb.append(curMap.get(key));
} else {
sb.append("---");
}
sb.append("</code1>");
sb.append(CRLF);
sb.append("<code2>");
if (cmpMap.containsKey(key)) {
sb.append(cmpMap.get(key));
} else {
sb.append("---");
}
sb.append("</code2>");
sb.append(CRLF);
sb.append("</urlrow>");
sb.append(CRLF);
}
sb.append("</report>");
sb.append(CRLF);
String fileName = "reportCompare.xsl";
Path xslFile = Paths.get(Constant.getZapInstall(), "xml", fileName);
if (Files.exists(xslFile)) {
stringToHtml(sb.toString(), xslFile.toString(), outputFile.getAbsolutePath());
} else {
String path = "/org/zaproxy/zap/resources/xml/" + fileName;
try (InputStream is = ExtensionCompare.class.getResourceAsStream(path)) {
if (is == null) {
log.error("Bundled file not found: " + path);
return;
}
stringToHtml(sb.toString(), new StreamSource(is), outputFile.getAbsolutePath());
}
}
if (Files.notExists(outputFile.toPath())) {
log.info("Not opening report, does not exist: " + outputFile);
return;
}
try {
DesktopUtils.openUrlInBrowser(outputFile.toURI());
} catch (Exception e) {
log.error(e.getMessage(), e);
getView().showMessageDialog(Constant.messages.getString("report.complete.warning", outputFile.getAbsolutePath()));
}
} catch (Exception e1) {
log.warn(e1.getMessage(), e1);
}
}
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
}
}
Aggregations