getRequireAlerts() {
- return requireAlertTasks;
- }
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/AlertTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/AlertTask.java
deleted file mode 100644
index b94fb63..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/AlertTask.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.Task;
-
-public class AlertTask extends Task {
- private String alert;
- private String risk;
- /**
- * @deprecated
- * Use of reliability has been deprecated in favour of using confidence
- */
- @Deprecated
- private String reliability;
- private String confidence;
- private String url;
- private String other;
- private String param;
-
- public String getAlert() {
- return alert;
- }
- public void setAlert(String alert) {
- this.alert = alert;
- }
- public String getRisk() {
- return risk;
- }
- public void setRisk(String risk) {
- this.risk = risk;
- }
- /**
- * @deprecated (2.4.0) {@link #getConfidence()}.
- * Use of reliability has been deprecated in favour of using confidence.
- */
- @Deprecated
- public String getReliability() {
- return reliability;
- }
- /**
- * @deprecated (2.4.0) Replaced by {@link #setConfidence(String)}
- * Use of reliability has been deprecated in favour of using confidence
- */
- @Deprecated
- public void setReliability(String reliability) {
- this.reliability = reliability;
- }
- public String getConfidence() {
- return confidence;
- }
- public void setConfidence(String confidence) {
- this.confidence = confidence;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public String getOther() {
- return other;
- }
- public void setOther(String other) {
- this.other = other;
- }
- public String getParam() {
- return param;
- }
- public void setParam(String param) {
- this.param = param;
- }
-
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/LoadSessionTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/LoadSessionTask.java
deleted file mode 100644
index aa8be39..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/LoadSessionTask.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.BuildException;
-
-public class LoadSessionTask extends ZapTask {
-
- private String name;
- private String apikey;
-
- @Override
- public void execute() throws BuildException {
- try {
- this.getClientApi().core.loadSession(apikey, name);
-
- } catch (Exception e) {
- throw new BuildException(e);
- }
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getApikey() {
- return apikey;
- }
-
- public void setApikey(String apikey) {
- this.apikey = apikey;
- }
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/NewSessionTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/NewSessionTask.java
deleted file mode 100644
index fa1ceec..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/NewSessionTask.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.BuildException;
-
-public class NewSessionTask extends ZapTask {
-
- private String name;
- private String apikey;
-
- @Override
- public void execute() throws BuildException {
- try {
- this.getClientApi().core.newSession(apikey, name, "true");
-
- } catch (Exception e) {
- throw new BuildException(e);
- }
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getApikey() {
- return apikey;
- }
-
- public void setApikey(String apikey) {
- this.apikey = apikey;
- }
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/SaveSessionTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/SaveSessionTask.java
deleted file mode 100644
index 4649e58..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/SaveSessionTask.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.BuildException;
-
-public class SaveSessionTask extends ZapTask {
-
- private String name;
- private String apikey;
-
- @Override
- public void execute() throws BuildException {
- try {
- this.getClientApi().core.saveSession(apikey, name, "true");
-
- } catch (Exception e) {
- throw new BuildException(e);
- }
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getApikey() {
- return apikey;
- }
-
- public void setApikey(String apikey) {
- this.apikey = apikey;
- }
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/SpiderUrlTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/SpiderUrlTask.java
deleted file mode 100644
index 7ee5f01..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/SpiderUrlTask.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.BuildException;
-
-public class SpiderUrlTask extends ZapTask {
-
- private String url;
- private String apikey;
-
- @Override
- public void execute() throws BuildException {
- try {
- this.getClientApi().spider.scan(apikey, url, "", "", null, null);
-
- } catch (Exception e) {
- throw new BuildException(e);
- }
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getApikey() {
- return apikey;
- }
-
- public void setApikey(String apikey) {
- this.apikey = apikey;
- }
-
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/StopZapTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/StopZapTask.java
deleted file mode 100644
index 7978e30..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/StopZapTask.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.BuildException;
-
-public class StopZapTask extends ZapTask {
-
- private String apikey;
-
- @Override
- public void execute() throws BuildException {
- try {
- this.getClientApi().core.shutdown(apikey);
- } catch (Exception e) {
- e.printStackTrace();
- throw new BuildException(e);
- }
- }
-
- public String getApikey() {
- return apikey;
- }
-
- public void setApikey(String apikey) {
- this.apikey = apikey;
- }
-
-}
diff --git a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/ZapTask.java b/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/ZapTask.java
deleted file mode 100644
index af83eda..0000000
--- a/subprojects/zap-clientapi-ant/src/main/java/org/zaproxy/clientapi/ant/ZapTask.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.ant;
-
-import org.apache.tools.ant.Task;
-import org.zaproxy.clientapi.core.ClientApi;
-
-public abstract class ZapTask extends Task {
- private String zapAddress;
- private int zapPort;
- private boolean debug = false;
-
- protected ClientApi getClientApi() {
- return new ClientApi(zapAddress, zapPort, debug);
- }
-
- public String getZapAddress() {
- return zapAddress;
- }
- public void setZapAddress(String zapAddress) {
- this.zapAddress = zapAddress;
- }
- public int getZapPort() {
- return zapPort;
- }
- public void setZapPort(int zapPort) {
- this.zapPort = zapPort;
- }
-
- public boolean isDebug() {
- return debug;
- }
-
- public void setDebug(boolean debug) {
- this.debug = debug;
- }
-}
diff --git a/subprojects/zap-clientapi-ant/zap-clientapi-ant.gradle b/subprojects/zap-clientapi-ant/zap-clientapi-ant.gradle
deleted file mode 100644
index d1b73e2..0000000
--- a/subprojects/zap-clientapi-ant/zap-clientapi-ant.gradle
+++ /dev/null
@@ -1,17 +0,0 @@
-
-version '1.0.1-SNAPSHOT'
-
-dependencies {
- compile project(':zap-clientapi')
- compileOnly 'org.apache.ant:ant:1.9.7'
-}
-
-sourceSets { examples }
-
-jar {
- manifest {
- attributes 'Implementation-Title': 'OWASP ZAP Ant API Client',
- 'Implementation-Version': version,
- 'Create-Date': new Date().format("yyyy-MM-dd")
- }
-}
diff --git a/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/SimpleExample.java b/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/SimpleExample.java
index 7142ab8..cb3715a 100644
--- a/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/SimpleExample.java
+++ b/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/SimpleExample.java
@@ -1,92 +1,111 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2016 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.examples;
-
-import org.zaproxy.clientapi.core.ApiResponse;
-import org.zaproxy.clientapi.core.ApiResponseElement;
-import org.zaproxy.clientapi.core.ClientApi;
-
-/**
- * A simple example showing how to use the API to spider and active scan a site and then retrieve and print out the alerts.
- *
- * ZAP must be running on the specified host and port for this script to work
- */
-public class SimpleExample {
-
- private static final String ZAP_ADDRESS = "localhost";
- private static final int ZAP_PORT = 8090;
- private static final String ZAP_API_KEY = null; // Change this if you have set the apikey in ZAP via Options / API
-
- private static final String TARGET = "http://localhost:8080/bodgeit/";
-
- public static void main(String[] args) {
- ClientApi api = new ClientApi(ZAP_ADDRESS, ZAP_PORT);
-
- try {
- // Start spidering the target
- System.out.println("Spider : " + TARGET);
- ApiResponse resp = api.spider.scan(ZAP_API_KEY, TARGET, null, null, null, null);
- String scanid;
- int progress;
-
- // The scan now returns a scan id to support concurrent scanning
- scanid = ((ApiResponseElement) resp).getValue();
-
- // Poll the status until it completes
- while (true) {
- Thread.sleep(1000);
- progress = Integer.parseInt(((ApiResponseElement) api.spider.status(scanid)).getValue());
- System.out.println("Spider progress : " + progress + "%");
- if (progress >= 100) {
- break;
- }
- }
- System.out.println("Spider complete");
-
- // Give the passive scanner a chance to complete
- Thread.sleep(2000);
-
- System.out.println("Active scan : " + TARGET);
- resp = api.ascan.scan(ZAP_API_KEY, TARGET, "True", "False", null, null, null);
-
- // The scan now returns a scan id to support concurrent scanning
- scanid = ((ApiResponseElement) resp).getValue();
-
- // Poll the status until it completes
- while (true) {
- Thread.sleep(5000);
- progress = Integer.parseInt(((ApiResponseElement) api.ascan.status(scanid)).getValue());
- System.out.println("Active Scan progress : " + progress + "%");
- if (progress >= 100) {
- break;
- }
- }
- System.out.println("Active Scan complete");
-
- System.out.println("Alerts:");
- System.out.println(new String(api.core.xmlreport(ZAP_API_KEY)));
-
- } catch (Exception e) {
- System.out.println("Exception : " + e.getMessage());
- e.printStackTrace();
- }
- }
-
-}
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2016 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.examples;
+
+import java.nio.charset.StandardCharsets;
+import org.zaproxy.clientapi.core.ApiResponse;
+import org.zaproxy.clientapi.core.ApiResponseElement;
+import org.zaproxy.clientapi.core.ClientApi;
+
+/**
+ * A simple example showing how to use the API to spider and active scan a site and then retrieve
+ * and print out the alerts.
+ *
+ *
ZAP must be running on the specified host and port for this script to work
+ */
+public class SimpleExample {
+
+ private static final String ZAP_ADDRESS = "localhost";
+ private static final int ZAP_PORT = 8090;
+ private static final String ZAP_API_KEY =
+ null; // Change this if you have set the apikey in ZAP via Options / API
+
+ private static final String TARGET = "http://localhost:8080/bodgeit/";
+
+ @SuppressWarnings("deprecation")
+ public static void main(String[] args) {
+ ClientApi api = new ClientApi(ZAP_ADDRESS, ZAP_PORT, ZAP_API_KEY);
+
+ try {
+ // Start spidering the target
+ System.out.println("Spider : " + TARGET);
+ // It's not necessary to pass the ZAP API key again, already set when creating the
+ // ClientApi.
+ ApiResponse resp = api.spider.scan(TARGET, null, null, null, null);
+ String scanid;
+ int progress;
+
+ // The scan now returns a scan id to support concurrent scanning
+ scanid = ((ApiResponseElement) resp).getValue();
+
+ // Poll the status until it completes
+ while (true) {
+ Thread.sleep(1000);
+ progress =
+ Integer.parseInt(
+ ((ApiResponseElement) api.spider.status(scanid)).getValue());
+ System.out.println("Spider progress : " + progress + "%");
+ if (progress >= 100) {
+ break;
+ }
+ }
+ System.out.println("Spider complete");
+
+ // Poll the number of records the passive scanner still has to scan until it completes
+ while (true) {
+ Thread.sleep(1000);
+ progress =
+ Integer.parseInt(
+ ((ApiResponseElement) api.pscan.recordsToScan()).getValue());
+ System.out.println("Passive Scan progress : " + progress + " records left");
+ if (progress < 1) {
+ break;
+ }
+ }
+ System.out.println("Passive Scan complete");
+
+ System.out.println("Active scan : " + TARGET);
+ resp = api.ascan.scan(TARGET, "True", "False", null, null, null);
+
+ // The scan now returns a scan id to support concurrent scanning
+ scanid = ((ApiResponseElement) resp).getValue();
+
+ // Poll the status until it completes
+ while (true) {
+ Thread.sleep(5000);
+ progress =
+ Integer.parseInt(
+ ((ApiResponseElement) api.ascan.status(scanid)).getValue());
+ System.out.println("Active Scan progress : " + progress + "%");
+ if (progress >= 100) {
+ break;
+ }
+ }
+ System.out.println("Active Scan complete");
+
+ System.out.println("Alerts:");
+ System.out.println(new String(api.core.xmlreport(), StandardCharsets.UTF_8));
+
+ } catch (Exception e) {
+ System.out.println("Exception : " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/Test.java b/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/Test.java
deleted file mode 100644
index 2b085ae..0000000
--- a/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/Test.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.zaproxy.clientapi.examples;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.zaproxy.clientapi.core.Alert;
-import org.zaproxy.clientapi.core.ClientApi;
-import org.zaproxy.clientapi.core.Alert.Confidence;
-import org.zaproxy.clientapi.core.Alert.Risk;
-
-public class Test {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO List
- // High priority
- // * Start ZAP in background - task still waits! } Need docs?
- // * Get checkAlerts to work with inner elements }
- // Medium - tidy up
- // * Create min zapapi.jar
- // * Correct way of installing in Eclipse
- // Docs etc
- // * Full wave reg test
- // * Full wavsep reg test
- // * Documentation
- // Publicise
- // * Blog, tweet etc etc
- // * Work out priorities for extending api
- // * Complete tasks - more for internal use than anything else
-
- List ignoreAlerts = new ArrayList<>(2);
- ignoreAlerts.add(new Alert("Cookie set without HttpOnly flag", null, Risk.Low, Confidence.Medium, null, null));
- ignoreAlerts.add(new Alert(null, null, Risk.Low, Confidence.Medium, null, null));
-
- try {
- (new ClientApi("localhost", 8090)).checkAlerts(ignoreAlerts, null );
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- List requireAlerts = new ArrayList<>(1);
- //ignoreAlerts.add(new Alert(null, null, null, null, null, null));
- requireAlerts.add(new Alert("Not present", null, Risk.Low, Confidence.Medium, null, null));
- try {
- (new ClientApi("localhost", 8090)).checkAlerts(ignoreAlerts, requireAlerts);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-}
-
-}
diff --git a/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/authentication/FormBasedAuthentication.java b/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/authentication/FormBasedAuthentication.java
index 0ed3f11..af208d6 100644
--- a/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/authentication/FormBasedAuthentication.java
+++ b/subprojects/zap-clientapi/src/examples/java/org/zaproxy/clientapi/examples/authentication/FormBasedAuthentication.java
@@ -1,14 +1,15 @@
-/* Zed Attack Proxy (ZAP) and its related class files.
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
- * Copyright the ZAP development team
+ * Copyright 2014 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -20,9 +21,8 @@
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
-import java.util.LinkedList;
+import java.util.ArrayList;
import java.util.List;
-
import org.zaproxy.clientapi.core.ApiResponse;
import org.zaproxy.clientapi.core.ApiResponseElement;
import org.zaproxy.clientapi.core.ApiResponseList;
@@ -33,155 +33,181 @@
/**
* An example of how to set up authentication via the API and get information about existing
* configuration.
- *
- * Some important aspects regarding the Authentication API:
+ *
+ * Some important aspects regarding the Authentication API:
+ *
*
- * -
- * since the AuthenticationMethods are loaded dynamically, there's no way to generate a 'static' API
- * for each auth method. That's why, when setting up the authentication method, depending on the
- * method, different values are passed to the setAuthenticationMethod . This is where the
- * getSupportedAuthenticationMethods and getAuthenticationMethodConfigParams methods come into play.
- * Basically the first one gives a list of available/loaded authentication methods while the second
- * one gives info about the parameters required to configure each authentication method type.
- * - when setting up the authentication method for a context, the setAuthenticationMethod method
- * is used. It takes the context id on which we're working, the name of the authentication method
- * and a 'authMethodConfigParams' parameter which contains all the configuration for the method. The
- * format of the value passed for 'authMethodConfigParams' matches the www-form-urlencoded style:
- * parameterName = urlEncodedValue. Check out the referenced example to see how the configuration is
- * build for the BodgeIt store login. The pseudocode for generating the config would be:
- * paramA + "=" + urlEncode(paramAValue) + "&" + paramB + "=" + urlEncode(paramBValue) + ...
- *
- * -
- * for formBasedAuthentication, the places filled in with the credentials are marked via {%username%}
- * and {%password%}, in either the requestUrl or the requestBody
+ * - since the AuthenticationMethods are loaded dynamically, there's no way to generate a
+ * 'static' API for each auth method. That's why, when setting up the authentication method,
+ * depending on the method, different values are passed to the setAuthenticationMethod . This
+ * is where the getSupportedAuthenticationMethods and getAuthenticationMethodConfigParams
+ * methods come into play. Basically the first one gives a list of available/loaded
+ * authentication methods while the second one gives info about the parameters required to
+ * configure each authentication method type.
+ *
- when setting up the authentication method for a context, the setAuthenticationMethod method
+ * is used. It takes the context id on which we're working, the name of the authentication
+ * method and a 'authMethodConfigParams' parameter which contains all the configuration for
+ * the method. The format of the value passed for 'authMethodConfigParams' matches the
+ * www-form-urlencoded style: parameterName = urlEncodedValue. Check out the referenced
+ * example to see how the configuration is build for the BodgeIt store login. The pseudocode
+ * for generating the config would be:
+ *
+ * paramA + "=" + urlEncode(paramAValue) + "&" + paramB + "=" + urlEncode(paramBValue) + ...
+ *
+ * - for formBasedAuthentication, the places filled in with the credentials are marked via
+ * {%username%} and {%password%}, in either the requestUrl or the requestBody
*
*/
public class FormBasedAuthentication {
- private static final String ZAP_ADDRESS = "localhost";
- private static final int ZAP_PORT = 8090;
- private static final String ZAP_API_KEY = null;
-
- private static void listAuthInformation(ClientApi clientApi) throws ClientApiException {
- // Check out which authentication methods are supported by the API
- List supportedMethodNames = new LinkedList<>();
- ApiResponseList authMethodsList = (ApiResponseList) clientApi.authentication.getSupportedAuthenticationMethods();
- for (ApiResponse authMethod : authMethodsList.getItems()) {
- supportedMethodNames.add(((ApiResponseElement) authMethod).getValue());
- }
- System.out.println("Supported authentication methods: " + supportedMethodNames);
-
- // Check out which are the config parameters of the authentication methods
- for (String methodName : supportedMethodNames) {
-
- ApiResponseList configParamsList = (ApiResponseList) clientApi.authentication
- .getAuthenticationMethodConfigParams(methodName);
-
- for (ApiResponse r : configParamsList.getItems()) {
- ApiResponseSet set = (ApiResponseSet) r;
- System.out.println("'" + methodName + "' config param: " + set.getValue("name") + " ("
- + (set.getValue("mandatory").equals("true") ? "mandatory" : "optional") + ")");
- }
- }
- }
-
- private static void listUserConfigInformation(ClientApi clientApi) throws ClientApiException {
- // Check out which are the config parameters required to set up an user with the currently
- // set authentication methods
- String contextId = "1";
- ApiResponseList configParamsList = (ApiResponseList) clientApi.users
- .getAuthenticationCredentialsConfigParams(contextId);
-
- StringBuilder sb = new StringBuilder("Users' config params: ");
- for (ApiResponse r : configParamsList.getItems()) {
- ApiResponseSet set = (ApiResponseSet) r;
- sb.append(set.getValue("name")).append(" (");
- sb.append((set.getValue("mandatory").equals("true") ? "mandatory" : "optional"));
- sb.append("), ");
- }
- System.out.println(sb.deleteCharAt(sb.length() - 2).toString());
- }
-
- private static void setLoggedInIndicator(ClientApi clientApi) throws ClientApiException {
- // Prepare values to set, with the logged in indicator as a regex matching the logout link
- String loggedInIndicator = "";
- String contextId = "1";
-
- // Actually set the logged in indicator
- clientApi.authentication.setLoggedInIndicator(ZAP_API_KEY, contextId, java.util.regex.Pattern.quote(loggedInIndicator));
-
- // Check out the logged in indicator that is set
- System.out.println("Configured logged in indicator regex: "
- + ((ApiResponseElement) clientApi.authentication.getLoggedInIndicator(contextId)).getValue());
- }
-
- private static void setFormBasedAuthenticationForBodgeit(ClientApi clientApi) throws ClientApiException,
- UnsupportedEncodingException {
- // Setup the authentication method
- String contextId = "1";
- String loginUrl = "http://localhost:8080/bodgeit/login.jsp";
- String loginRequestData = "username={%username%}&password={%password%}";
-
- // Prepare the configuration in a format similar to how URL parameters are formed. This
- // means that any value we add for the configuration values has to be URL encoded.
- StringBuilder formBasedConfig = new StringBuilder();
- formBasedConfig.append("loginUrl=").append(URLEncoder.encode(loginUrl, "UTF-8"));
- formBasedConfig.append("&loginRequestData=").append(URLEncoder.encode(loginRequestData, "UTF-8"));
-
- System.out.println("Setting form based authentication configuration as: "
- + formBasedConfig.toString());
- clientApi.authentication.setAuthenticationMethod(ZAP_API_KEY, contextId, "formBasedAuthentication",
- formBasedConfig.toString());
-
- // Check if everything is set up ok
- System.out
- .println("Authentication config: " + clientApi.authentication.getAuthenticationMethod(contextId).toString(0));
- }
-
- private static void setUserAuthConfigForBodgeit(ClientApi clientApi) throws ClientApiException, UnsupportedEncodingException {
- // Prepare info
- String contextId = "1";
- String user = "Test User";
- String username = "test@example.com";
- String password = "weakPassword";
-
- // Make sure we have at least one user
- String userId = extractUserId(clientApi.users.newUser(ZAP_API_KEY, contextId, user));
-
- // Prepare the configuration in a format similar to how URL parameters are formed. This
- // means that any value we add for the configuration values has to be URL encoded.
- StringBuilder userAuthConfig = new StringBuilder();
- userAuthConfig.append("username=").append(URLEncoder.encode(username, "UTF-8"));
- userAuthConfig.append("&password=").append(URLEncoder.encode(password, "UTF-8"));
-
- System.out.println("Setting user authentication configuration as: " + userAuthConfig.toString());
- clientApi.users.setAuthenticationCredentials(ZAP_API_KEY, contextId, userId, userAuthConfig.toString());
-
- // Check if everything is set up ok
- System.out.println("Authentication config: " + clientApi.users.getUserById(contextId, userId).toString(0));
- }
-
- private static String extractUserId(ApiResponse response) {
- return ((ApiResponseElement) response).getValue();
- }
-
- /**
- * The main method.
- *
- * @param args the arguments
- * @throws Exception if an error occurred while accessing the API
- */
- public static void main(String[] args) throws Exception {
- ClientApi clientApi = new ClientApi(ZAP_ADDRESS, ZAP_PORT);
-
- listAuthInformation(clientApi);
- System.out.println("-------------");
- setFormBasedAuthenticationForBodgeit(clientApi);
- System.out.println("-------------");
- setLoggedInIndicator(clientApi);
- System.out.println("-------------");
- listUserConfigInformation(clientApi);
- System.out.println("-------------");
- setUserAuthConfigForBodgeit(clientApi);
- }
+ private static final String ZAP_ADDRESS = "localhost";
+ private static final int ZAP_PORT = 8090;
+ private static final String ZAP_API_KEY = null;
+
+ private static void listAuthInformation(ClientApi clientApi) throws ClientApiException {
+ // Check out which authentication methods are supported by the API
+ List supportedMethodNames = new ArrayList<>();
+ ApiResponseList authMethodsList =
+ (ApiResponseList) clientApi.authentication.getSupportedAuthenticationMethods();
+ for (ApiResponse authMethod : authMethodsList.getItems()) {
+ supportedMethodNames.add(((ApiResponseElement) authMethod).getValue());
+ }
+ System.out.println("Supported authentication methods: " + supportedMethodNames);
+
+ // Check out which are the config parameters of the authentication methods
+ for (String methodName : supportedMethodNames) {
+
+ ApiResponseList configParamsList =
+ (ApiResponseList)
+ clientApi.authentication.getAuthenticationMethodConfigParams(
+ methodName);
+
+ for (ApiResponse r : configParamsList.getItems()) {
+ ApiResponseSet set = (ApiResponseSet) r;
+ System.out.println(
+ "'"
+ + methodName
+ + "' config param: "
+ + set.getValue("name")
+ + " ("
+ + (set.getStringValue("mandatory").equals("true")
+ ? "mandatory"
+ : "optional")
+ + ")");
+ }
+ }
+ }
+
+ private static void listUserConfigInformation(ClientApi clientApi) throws ClientApiException {
+ // Check out which are the config parameters required to set up an user with the currently
+ // set authentication methods
+ String contextId = "1";
+ ApiResponseList configParamsList =
+ (ApiResponseList)
+ clientApi.users.getAuthenticationCredentialsConfigParams(contextId);
+
+ StringBuilder sb = new StringBuilder("Users' config params: ");
+ for (ApiResponse r : configParamsList.getItems()) {
+ ApiResponseSet set = (ApiResponseSet) r;
+ sb.append(set.getValue("name")).append(" (");
+ sb.append((set.getStringValue("mandatory").equals("true") ? "mandatory" : "optional"));
+ sb.append("), ");
+ }
+ System.out.println(sb.deleteCharAt(sb.length() - 2).toString());
+ }
+
+ private static void setLoggedInIndicator(ClientApi clientApi) throws ClientApiException {
+ // Prepare values to set, with the logged in indicator as a regex matching the logout link
+ String loggedInIndicator = "";
+ String contextId = "1";
+
+ // Actually set the logged in indicator
+ clientApi.authentication.setLoggedInIndicator(
+ contextId, java.util.regex.Pattern.quote(loggedInIndicator));
+
+ // Check out the logged in indicator that is set
+ System.out.println(
+ "Configured logged in indicator regex: "
+ + ((ApiResponseElement)
+ clientApi.authentication.getLoggedInIndicator(contextId))
+ .getValue());
+ }
+
+ private static void setFormBasedAuthenticationForBodgeit(ClientApi clientApi)
+ throws ClientApiException, UnsupportedEncodingException {
+ // Setup the authentication method
+ String contextId = "1";
+ String loginUrl = "http://localhost:8080/bodgeit/login.jsp";
+ String loginRequestData = "username={%username%}&password={%password%}";
+
+ // Prepare the configuration in a format similar to how URL parameters are formed. This
+ // means that any value we add for the configuration values has to be URL encoded.
+ StringBuilder formBasedConfig = new StringBuilder();
+ formBasedConfig.append("loginUrl=").append(URLEncoder.encode(loginUrl, "UTF-8"));
+ formBasedConfig
+ .append("&loginRequestData=")
+ .append(URLEncoder.encode(loginRequestData, "UTF-8"));
+
+ System.out.println(
+ "Setting form based authentication configuration as: "
+ + formBasedConfig.toString());
+ clientApi.authentication.setAuthenticationMethod(
+ contextId, "formBasedAuthentication", formBasedConfig.toString());
+
+ // Check if everything is set up ok
+ System.out.println(
+ "Authentication config: "
+ + clientApi.authentication.getAuthenticationMethod(contextId).toString(0));
+ }
+
+ private static void setUserAuthConfigForBodgeit(ClientApi clientApi)
+ throws ClientApiException, UnsupportedEncodingException {
+ // Prepare info
+ String contextId = "1";
+ String user = "Test User";
+ String username = "test@example.com";
+ String password = "weakPassword";
+
+ // Make sure we have at least one user
+ String userId = extractUserId(clientApi.users.newUser(contextId, user));
+
+ // Prepare the configuration in a format similar to how URL parameters are formed. This
+ // means that any value we add for the configuration values has to be URL encoded.
+ StringBuilder userAuthConfig = new StringBuilder();
+ userAuthConfig.append("username=").append(URLEncoder.encode(username, "UTF-8"));
+ userAuthConfig.append("&password=").append(URLEncoder.encode(password, "UTF-8"));
+
+ System.out.println(
+ "Setting user authentication configuration as: " + userAuthConfig.toString());
+ clientApi.users.setAuthenticationCredentials(contextId, userId, userAuthConfig.toString());
+
+ // Check if everything is set up ok
+ System.out.println(
+ "Authentication config: "
+ + clientApi.users.getUserById(contextId, userId).toString(0));
+ }
+
+ private static String extractUserId(ApiResponse response) {
+ return ((ApiResponseElement) response).getValue();
+ }
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ * @throws Exception if an error occurred while accessing the API
+ */
+ public static void main(String[] args) throws Exception {
+ ClientApi clientApi = new ClientApi(ZAP_ADDRESS, ZAP_PORT, ZAP_API_KEY);
+
+ listAuthInformation(clientApi);
+ System.out.println("-------------");
+ setFormBasedAuthenticationForBodgeit(clientApi);
+ System.out.println("-------------");
+ setLoggedInIndicator(clientApi);
+ System.out.println("-------------");
+ listUserConfigInformation(clientApi);
+ System.out.println("-------------");
+ setUserAuthConfigForBodgeit(clientApi);
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/Alert.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/Alert.java
index a4dfd1b..f9a585b 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/Alert.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/Alert.java
@@ -1,360 +1,551 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.core;
-
-
-public class Alert {
-
- public enum Risk {Informational, Low, Medium, High};
- /**
- * @deprecated (2.4.0) Replaced by {@link Confidence}.
- * Use of reliability has been deprecated in favour of using confidence.
- */
- @Deprecated
- public enum Reliability {Suspicious, Warning};
- public enum Confidence {Low, Medium, High, Confirmed};
-
- private String alert;
- private Risk risk;
- /**
- * @deprecated (2.4.0) Replaced by {@link Confidence}.
- * Use of reliability has been deprecated in favour of using confidence
- */
- @Deprecated
- private Reliability reliability;
- private Confidence confidence;
- private String url;
- private String other;
- private String param;
- private String attack;
- private String evidence;
- private String description;
- private String reference;
- private String solution;
- private int cweId;
- private int wascId;
-
- public Alert(String alert, String url, String riskStr, String confidenceStr,
- String param, String other) {
- super();
- this.alert = alert;
- this.url = url;
- this.other = other;
- this.param = param;
- if (riskStr != null) {
- this.risk = Risk.valueOf(riskStr);
- }
- if (confidenceStr != null) {
- this.confidence = Confidence.valueOf(confidenceStr);
- }
- }
-
- public Alert(String alert, String url, Risk risk, Confidence confidence,
- String param, String other, String attack, String description, String reference, String solution,
- String evidence, int cweId, int wascId) {
- super();
- this.alert = alert;
- this.risk = risk;
- this.confidence = confidence;
- this.url = url;
- this.other = other;
- this.param = param;
- this.attack = attack;
- this.description = description;
- this.reference = reference;
- this.solution = solution;
- this.evidence = evidence;
- this.cweId = cweId;
- this.wascId = wascId;
- }
-
- public Alert(String alert, String url, Risk risk, Confidence confidence,
- String param, String other) {
- super();
- this.alert = alert;
- this.risk = risk;
- this.confidence = confidence;
- this.url = url;
- this.other = other;
- this.param = param;
- }
-
- public Alert(String alert, String url, Risk risk, Confidence confidence) {
- super();
- this.alert = alert;
- this.risk = risk;
- this.confidence = confidence;
- this.url = url;
- }
-
- public Alert(String alert, String url) {
- super();
- this.alert = alert;
- this.url = url;
- }
-
- public String getAlert() {
- return alert;
- }
- public void setAlert(String alert) {
- this.alert = alert;
- }
- public Risk getRisk() {
- return risk;
- }
- public void setRisk(Risk risk) {
- this.risk = risk;
- }
- public void setRisk(String risk) {
- this.risk = Risk.valueOf(risk);
- }
- /**
- * @deprecated
- * {@link #getConfidence()}
- * Use of reliability has been deprecated in favour of using confidence
- */
- @Deprecated
- public Reliability getReliability() {
- return reliability;
- }
- /**
- * @deprecated
- * {@link #setConfidence(Confidence)}
- * Use of reliability has been deprecated in favour of using confidence
- */
- @Deprecated
- public void setReliability(Reliability reliability) {
- this.reliability = reliability;
- }
- /**
- * @deprecated
- * {@link #setConfidence(String)}
- * Use of reliability has been deprecated in favour of using confidence
- */
- @Deprecated
- public void setReliability(String reliability) {
- this.reliability = Reliability.valueOf(reliability);
- }
- public Confidence getConfidence() {
- return confidence;
- }
- public void setConfidence(Confidence confidence) {
- this.confidence = confidence;
- }
- public void setConfidence(String confidence) {
- this.confidence = Confidence.valueOf(confidence);
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public String getOther() {
- return other;
- }
- public void setOther(String other) {
- this.other = other;
- }
- public String getParam() {
- return param;
- }
- public void setParam(String param) {
- this.param = param;
- }
-
- public String getAttack() {
- return attack;
- }
-
- public String getDescription() {
- return description;
- }
-
- public String getReference() {
- return reference;
- }
-
- public String getSolution() {
- return solution;
- }
-
- public String getEvidence() {
- return evidence;
- }
-
- public int getCweId() {
- return cweId;
- }
-
- public int getWascId() {
- return wascId;
- }
-
- public boolean matches (Alert alertFilter) {
- boolean matches = true;
- if (alertFilter.getAlert() != null && ! alertFilter.getAlert().equals(alert) ) {
- matches = false;
- }
- if (alertFilter.getRisk() != null && ! alertFilter.getRisk().equals(risk) ) {
- matches = false;
- }
- if (alertFilter.getConfidence() != null && ! alertFilter.getConfidence().equals(confidence) ) {
- matches = false;
- }
-
- return matches;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((alert == null) ? 0 : alert.hashCode());
- result = prime * result + ((attack == null) ? 0 : attack.hashCode());
- result = prime * result + cweId;
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((evidence == null) ? 0 : evidence.hashCode());
- result = prime * result + ((other == null) ? 0 : other.hashCode());
- result = prime * result + ((param == null) ? 0 : param.hashCode());
- result = prime * result + ((reference == null) ? 0 : reference.hashCode());
- result = prime * result + ((confidence == null) ? 0 : confidence.hashCode());
- result = prime * result + ((risk == null) ? 0 : risk.hashCode());
- result = prime * result + ((solution == null) ? 0 : solution.hashCode());
- result = prime * result + ((url == null) ? 0 : url.hashCode());
- result = prime * result + wascId;
- return result;
- }
-
- @Override
- public boolean equals(Object object) {
- if (this == object) {
- return true;
- }
- if (object == null) {
- return false;
- }
- if (getClass() != object.getClass()) {
- return false;
- }
- Alert otherAlert = (Alert) object;
- if (alert == null) {
- if (otherAlert.alert != null) {
- return false;
- }
- } else if (!alert.equals(otherAlert.alert)) {
- return false;
- }
- if (attack == null) {
- if (otherAlert.attack != null) {
- return false;
- }
- } else if (!attack.equals(otherAlert.attack)) {
- return false;
- }
- if (cweId != otherAlert.cweId) {
- return false;
- }
- if (description == null) {
- if (otherAlert.description != null) {
- return false;
- }
- } else if (!description.equals(otherAlert.description)) {
- return false;
- }
- if (evidence == null) {
- if (otherAlert.evidence != null) {
- return false;
- }
- } else if (!evidence.equals(otherAlert.evidence)) {
- return false;
- }
- if (this.other == null) {
- if (otherAlert.other != null) {
- return false;
- }
- } else if (!this.other.equals(otherAlert.other)) {
- return false;
- }
- if (param == null) {
- if (otherAlert.param != null) {
- return false;
- }
- } else if (!param.equals(otherAlert.param)) {
- return false;
- }
- if (reference == null) {
- if (otherAlert.reference != null) {
- return false;
- }
- } else if (!reference.equals(otherAlert.reference)) {
- return false;
- }
- if (confidence != otherAlert.confidence) {
- return false;
- }
- if (risk != otherAlert.risk) {
- return false;
- }
- if (solution == null) {
- if (otherAlert.solution != null) {
- return false;
- }
- } else if (!solution.equals(otherAlert.solution)) {
- return false;
- }
- if (url == null) {
- if (otherAlert.url != null) {
- return false;
- }
- } else if (!url.equals(otherAlert.url)) {
- return false;
- }
- if (wascId != otherAlert.wascId) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("\tAlert: ").append(getAlert()).append(", ");
- sb.append("Risk: ");
- if (getRisk() != null) {
- sb.append(getRisk().name());
- } else {
- sb.append("null");
- }
- sb.append(", ");
- sb.append("Confidence: ");
- if (getConfidence() != null) {
- sb.append(getConfidence().name());
- } else {
- sb.append("null");
- }
- sb.append(", ");
- sb.append("Url: ").append(getUrl()).append(", ");
- sb.append("Param: ").append(getParam()).append(", ");
- sb.append("Other: ").append(getOther());
- return sb.toString();
- }
-
-}
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2011 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.core;
+
+public class Alert {
+
+ public enum Risk {
+ Informational,
+ Low,
+ Medium,
+ High
+ }
+
+ /**
+ * @deprecated (2.4.0) Replaced by {@link Confidence}. Use of reliability has been deprecated in
+ * favour of using confidence.
+ */
+ @Deprecated
+ public enum Reliability {
+ Suspicious,
+ Warning
+ }
+
+ public enum Confidence {
+ FalsePositive,
+ Low,
+ Medium,
+ High,
+ Confirmed
+ }
+
+ private String id;
+ private String name;
+ private Risk risk;
+
+ /**
+ * @deprecated (2.4.0) Replaced by {@link Confidence}. Use of reliability has been deprecated in
+ * favour of using confidence
+ */
+ @Deprecated private Reliability reliability;
+
+ private Confidence confidence;
+ private String url;
+ private String other;
+ private String param;
+ private String attack;
+ private String evidence;
+ private String description;
+ private String reference;
+ private String solution;
+ private int cweId;
+ private int wascId;
+ private String messageId;
+ private String pluginId;
+
+ /**
+ * Constructs an {@code Alert} from the given {@code ApiResponseSet}.
+ *
+ * @param apiResponseSet the {@code ApiResponseSet} returned from an alert related ZAP API call.
+ * @since 1.1.0
+ */
+ public Alert(ApiResponseSet apiResponseSet) {
+ super();
+ this.id = apiResponseSet.getStringValue("id");
+ this.pluginId = apiResponseSet.getStringValue("pluginId");
+ String name = apiResponseSet.getStringValue("name");
+ if (name == null) {
+ // TODO Remove once alert attribute is no longer supported.
+ name = apiResponseSet.getStringValue("alert");
+ }
+ this.name = name;
+ this.description = apiResponseSet.getStringValue("description");
+ this.risk = stringToRisk(apiResponseSet.getStringValue("risk"));
+ this.confidence = stringToConfidence(apiResponseSet.getStringValue("confidence"));
+ this.url = apiResponseSet.getStringValue("url");
+ this.other = apiResponseSet.getStringValue("other");
+ this.param = apiResponseSet.getStringValue("param");
+ this.attack = apiResponseSet.getStringValue("attack");
+ this.evidence = apiResponseSet.getStringValue("evidence");
+ this.reference = apiResponseSet.getStringValue("reference");
+ this.cweId = stringToInt(apiResponseSet.getStringValue("cweid"), 0);
+ this.wascId = stringToInt(apiResponseSet.getStringValue("wascid"), 0);
+ this.solution = apiResponseSet.getStringValue("solution");
+ this.messageId = apiResponseSet.getStringValue("messageId");
+ }
+
+ public Alert(
+ String name,
+ String url,
+ String riskStr,
+ String confidenceStr,
+ String param,
+ String other) {
+ super();
+ this.name = name;
+ this.url = url;
+ this.other = other;
+ this.param = param;
+ this.risk = stringToRisk(riskStr);
+ this.confidence = stringToConfidence(confidenceStr);
+ }
+
+ public Alert(
+ String name,
+ String url,
+ Risk risk,
+ Confidence confidence,
+ String param,
+ String other,
+ String attack,
+ String description,
+ String reference,
+ String solution,
+ String evidence,
+ int cweId,
+ int wascId) {
+ super();
+ this.name = name;
+ this.risk = risk;
+ this.confidence = confidence;
+ this.url = url;
+ this.other = other;
+ this.param = param;
+ this.attack = attack;
+ this.description = description;
+ this.reference = reference;
+ this.solution = solution;
+ this.evidence = evidence;
+ this.cweId = cweId;
+ this.wascId = wascId;
+ }
+
+ public Alert(
+ String name, String url, Risk risk, Confidence confidence, String param, String other) {
+ super();
+ this.name = name;
+ this.risk = risk;
+ this.confidence = confidence;
+ this.url = url;
+ this.other = other;
+ this.param = param;
+ }
+
+ public Alert(String name, String url, Risk risk, Confidence confidence) {
+ super();
+ this.name = name;
+ this.risk = risk;
+ this.confidence = confidence;
+ this.url = url;
+ }
+
+ public Alert(String name, String url) {
+ super();
+ this.name = name;
+ this.url = url;
+ }
+
+ /**
+ * Converts the given {@code string} to an {@code int}.
+ *
+ * If the given {@code string} is {@code null} or not a valid {@code int}, the default value
+ * is returned.
+ *
+ * @param string the string to be converted to {@code int}.
+ * @param defaultValue the value to return in case the {@code string} is {@code null} or not an
+ * {@code int}.
+ * @return the {@code int} converted from the {@code string}, or the default value if {@code
+ * string} is {@code null} or not an {@code int}.
+ */
+ private static int stringToInt(String string, int defaultValue) {
+ if (string == null) {
+ return defaultValue;
+ }
+ try {
+ return Integer.parseInt(string);
+ } catch (NumberFormatException e) {
+ // Ignore.
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Converts the given {@code string} to a {@link Risk} value.
+ *
+ * @param string the string to be converted to a {@link Risk} value.
+ * @return the {@code Risk} value converted from the {@code string}, or null if {@code string}
+ * is {@code null}.
+ */
+ private static Risk stringToRisk(String string) {
+ if (string == null) {
+ return null;
+ }
+ return Risk.valueOf(string);
+ }
+
+ /**
+ * Converts the given {@code string} to a {@link Confidence} value.
+ *
+ * @param string the string to be converted to a {@link Confidence} value.
+ * @return the {@code Confidence} value converted from the {@code string}, or null if {@code
+ * string} is {@code null}.
+ */
+ private static Confidence stringToConfidence(String string) {
+ if (string == null) {
+ return null;
+ }
+ if ("False Positive".equalsIgnoreCase(string)) {
+ return Confidence.FalsePositive;
+ }
+ return Confidence.valueOf(string);
+ }
+
+ /**
+ * Gets the ID of the alert.
+ *
+ * @return the ID of the alert.
+ * @since 1.1.0
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * Gets the ID of the plugin/scanner that raised the alert.
+ *
+ * @return the ID of the plugin/scanner that raised the alert.
+ * @since 1.1.0
+ */
+ public String getPluginId() {
+ return pluginId;
+ }
+
+ /**
+ * Gets the ID of the HTTP message of the alert.
+ *
+ * @return the ID of the HTTP message.
+ * @since 1.1.0
+ */
+ public String getMessageId() {
+ return messageId;
+ }
+
+ /**
+ * Gets the name of the alert.
+ *
+ * @return the name of the alert
+ * @since 1.1.0
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the name of the alert.
+ *
+ * @param name the name of the alert
+ * @since 1.1.0
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Gets the name of the alert.
+ *
+ * @return the name of the alert
+ * @deprecated (1.1.0) Use {@link #getName()} instead.
+ */
+ @Deprecated
+ public String getAlert() {
+ return name;
+ }
+
+ /**
+ * Sets the name of the alert.
+ *
+ * @param name the name of the alert
+ * @deprecated (1.1.0) Use {@link #setName(String)} instead.
+ */
+ @Deprecated
+ public void setAlert(String name) {
+ this.name = name;
+ }
+
+ public Risk getRisk() {
+ return risk;
+ }
+
+ public void setRisk(Risk risk) {
+ this.risk = risk;
+ }
+
+ public void setRisk(String risk) {
+ this.risk = Risk.valueOf(risk);
+ }
+
+ /**
+ * @deprecated {@link #getConfidence()} Use of reliability has been deprecated in favour of
+ * using confidence
+ */
+ @Deprecated
+ public Reliability getReliability() {
+ return reliability;
+ }
+
+ /**
+ * @deprecated {@link #setConfidence(Confidence)} Use of reliability has been deprecated in
+ * favour of using confidence
+ */
+ @Deprecated
+ public void setReliability(Reliability reliability) {
+ this.reliability = reliability;
+ }
+
+ /**
+ * @deprecated {@link #setConfidence(String)} Use of reliability has been deprecated in favour
+ * of using confidence
+ */
+ @Deprecated
+ public void setReliability(String reliability) {
+ this.reliability = Reliability.valueOf(reliability);
+ }
+
+ public Confidence getConfidence() {
+ return confidence;
+ }
+
+ public void setConfidence(Confidence confidence) {
+ this.confidence = confidence;
+ }
+
+ public void setConfidence(String confidence) {
+ this.confidence = Confidence.valueOf(confidence);
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getOther() {
+ return other;
+ }
+
+ public void setOther(String other) {
+ this.other = other;
+ }
+
+ public String getParam() {
+ return param;
+ }
+
+ public void setParam(String param) {
+ this.param = param;
+ }
+
+ public String getAttack() {
+ return attack;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getReference() {
+ return reference;
+ }
+
+ public String getSolution() {
+ return solution;
+ }
+
+ public String getEvidence() {
+ return evidence;
+ }
+
+ public int getCweId() {
+ return cweId;
+ }
+
+ public int getWascId() {
+ return wascId;
+ }
+
+ public boolean matches(Alert alertFilter) {
+ boolean matches = true;
+ if (alertFilter.getName() != null && !alertFilter.getName().equals(name)) {
+ matches = false;
+ }
+ if (alertFilter.getRisk() != null && !alertFilter.getRisk().equals(risk)) {
+ matches = false;
+ }
+ if (alertFilter.getConfidence() != null
+ && !alertFilter.getConfidence().equals(confidence)) {
+ matches = false;
+ }
+
+ return matches;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((attack == null) ? 0 : attack.hashCode());
+ result = prime * result + cweId;
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + ((evidence == null) ? 0 : evidence.hashCode());
+ result = prime * result + ((other == null) ? 0 : other.hashCode());
+ result = prime * result + ((param == null) ? 0 : param.hashCode());
+ result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+ result = prime * result + ((confidence == null) ? 0 : confidence.hashCode());
+ result = prime * result + ((risk == null) ? 0 : risk.hashCode());
+ result = prime * result + ((solution == null) ? 0 : solution.hashCode());
+ result = prime * result + ((url == null) ? 0 : url.hashCode());
+ result = prime * result + wascId;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (!(object instanceof Alert)) {
+ return false;
+ }
+ Alert otherAlert = (Alert) object;
+ if (name == null) {
+ if (otherAlert.name != null) {
+ return false;
+ }
+ } else if (!name.equals(otherAlert.name)) {
+ return false;
+ }
+ if (attack == null) {
+ if (otherAlert.attack != null) {
+ return false;
+ }
+ } else if (!attack.equals(otherAlert.attack)) {
+ return false;
+ }
+ if (cweId != otherAlert.cweId) {
+ return false;
+ }
+ if (description == null) {
+ if (otherAlert.description != null) {
+ return false;
+ }
+ } else if (!description.equals(otherAlert.description)) {
+ return false;
+ }
+ if (evidence == null) {
+ if (otherAlert.evidence != null) {
+ return false;
+ }
+ } else if (!evidence.equals(otherAlert.evidence)) {
+ return false;
+ }
+ if (this.other == null) {
+ if (otherAlert.other != null) {
+ return false;
+ }
+ } else if (!this.other.equals(otherAlert.other)) {
+ return false;
+ }
+ if (param == null) {
+ if (otherAlert.param != null) {
+ return false;
+ }
+ } else if (!param.equals(otherAlert.param)) {
+ return false;
+ }
+ if (reference == null) {
+ if (otherAlert.reference != null) {
+ return false;
+ }
+ } else if (!reference.equals(otherAlert.reference)) {
+ return false;
+ }
+ if (confidence != otherAlert.confidence) {
+ return false;
+ }
+ if (risk != otherAlert.risk) {
+ return false;
+ }
+ if (solution == null) {
+ if (otherAlert.solution != null) {
+ return false;
+ }
+ } else if (!solution.equals(otherAlert.solution)) {
+ return false;
+ }
+ if (url == null) {
+ if (otherAlert.url != null) {
+ return false;
+ }
+ } else if (!url.equals(otherAlert.url)) {
+ return false;
+ }
+ if (wascId != otherAlert.wascId) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("\tAlert: ").append(getAlert()).append(", ");
+ sb.append("Risk: ");
+ if (getRisk() != null) {
+ sb.append(getRisk().name());
+ } else {
+ sb.append("null");
+ }
+ sb.append(", ");
+ sb.append("Confidence: ");
+ if (getConfidence() != null) {
+ sb.append(getConfidence().name());
+ } else {
+ sb.append("null");
+ }
+ sb.append(", ");
+ sb.append("Url: ").append(getUrl()).append(", ");
+ sb.append("Param: ").append(getParam()).append(", ");
+ sb.append("Other: ").append(getOther());
+ return sb.toString();
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/AlertsFile.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/AlertsFile.java
index f463db9..f2a8f2a 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/AlertsFile.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/AlertsFile.java
@@ -1,107 +1,134 @@
-package org.zaproxy.clientapi.core;
-
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.JDOMException;
-import org.jdom.input.SAXBuilder;
-import org.jdom.output.Format;
-import org.jdom.output.XMLOutputter;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-public class AlertsFile {
- public static void saveAlertsToFile(List requireAlerts, List reportAlerts, List ignoredAlerts, File outputFile) throws JDOMException, IOException {
- Element alerts = new Element("alerts");
- Document alertsDocument = new Document(alerts);
- alertsDocument.setRootElement(alerts);
- if (reportAlerts.size() > 0){
- Element alertsFound = new Element("alertsFound");
- alertsFound.setAttribute("alertsFound", Integer.toString(reportAlerts.size()));
- for (Alert alert : reportAlerts){
- createAlertXMLElements(alertsFound, alert);
- }
- alertsDocument.getRootElement().addContent(alertsFound);
- }
-
- if (requireAlerts.size() > 0){
- Element alertsNotFound = new Element("alertsNotFound");
- alertsNotFound.setAttribute("alertsNotFound", Integer.toString(requireAlerts.size()));
- for (Alert alert : requireAlerts){
- createAlertXMLElements(alertsNotFound, alert);
- }
- alertsDocument.getRootElement().addContent(alertsNotFound);
- }
-
- if (ignoredAlerts.size() > 0){
- Element ignoredAlertsFound = new Element("ignoredAlertsFound");
- ignoredAlertsFound.setAttribute("ignoredAlertsFound", Integer.toString(ignoredAlerts.size()));
- for (Alert alert : ignoredAlerts){
- createAlertXMLElements(ignoredAlertsFound, alert);
- }
- alertsDocument.getRootElement().addContent(ignoredAlertsFound);
- }
-
- writeAlertsToFile(outputFile, alertsDocument);
- }
-
- private static void writeAlertsToFile(File outputFile, Document doc) {
-
- XMLOutputter xmlOutput = new XMLOutputter();
-
- xmlOutput.setFormat(Format.getPrettyFormat());
- try {
- xmlOutput.output(doc, new FileWriter(outputFile));
- System.out.println("alert xml report saved to: "+outputFile.getAbsolutePath());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- private static void createAlertXMLElements(Element alertsFound, Alert alert) {
- Element alertElement = new Element("alert");
- if (alert.getAlert() != null)
- alertElement.setAttribute("alert", alert.getAlert());
- if (alert.getRisk() != null)
- alertElement.setAttribute("risk", alert.getRisk().name());
- if (alert.getUrl() != null)
- alertElement.setAttribute("confidence", alert.getConfidence().name());
- if (alert.getUrl() != null)
- alertElement.setAttribute("url", alert.getUrl());
- if (alert.getParam() != null)
- alertElement.setAttribute("param", alert.getParam());
- if (alert.getOther() != null)
- alertElement.setAttribute("other", alert.getOther());
- if (alert.getAttack() != null)
- alertElement.setAttribute("attack", alert.getAttack());
- if (alert.getDescription() != null)
- alertElement.setAttribute("description", alert.getDescription());
- if (alert.getSolution() != null)
- alertElement.setAttribute("solution", alert.getSolution());
- if (alert.getReference() != null)
- alertElement.setAttribute("reference", alert.getReference());
- alertsFound.addContent(alertElement);
- }
-
- public static List getAlertsFromFile(File file, String alertType) throws JDOMException, IOException {
- List alerts = new ArrayList<>();
- SAXBuilder parser = new SAXBuilder();
- Document alertsDoc = parser.build(file);
- @SuppressWarnings("unchecked")
- List alertElements = alertsDoc.getRootElement().getChildren(alertType);
- for (Element element: alertElements){
- Alert alert = new Alert(
- element.getAttributeValue("alert"),
- element.getAttributeValue("url"),
- element.getAttributeValue("risk"),
- element.getAttributeValue("confidence"),
- element.getAttributeValue("param"),
- element.getAttributeValue("other"));
- alerts.add(alert);
- }
- return alerts;
- }
-}
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.core;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.JDOMException;
+import org.jdom.input.SAXBuilder;
+import org.jdom.output.Format;
+import org.jdom.output.XMLOutputter;
+
+public class AlertsFile {
+ public static void saveAlertsToFile(
+ List requireAlerts,
+ List reportAlerts,
+ List ignoredAlerts,
+ File outputFile)
+ throws JDOMException, IOException {
+ Element alerts = new Element("alerts");
+ Document alertsDocument = new Document(alerts);
+ alertsDocument.setRootElement(alerts);
+ if (reportAlerts.size() > 0) {
+ Element alertsFound = new Element("alertsFound");
+ alertsFound.setAttribute("alertsFound", Integer.toString(reportAlerts.size()));
+ for (Alert alert : reportAlerts) {
+ createAlertXMLElements(alertsFound, alert);
+ }
+ alertsDocument.getRootElement().addContent(alertsFound);
+ }
+
+ if (requireAlerts.size() > 0) {
+ Element alertsNotFound = new Element("alertsNotFound");
+ alertsNotFound.setAttribute("alertsNotFound", Integer.toString(requireAlerts.size()));
+ for (Alert alert : requireAlerts) {
+ createAlertXMLElements(alertsNotFound, alert);
+ }
+ alertsDocument.getRootElement().addContent(alertsNotFound);
+ }
+
+ if (ignoredAlerts.size() > 0) {
+ Element ignoredAlertsFound = new Element("ignoredAlertsFound");
+ ignoredAlertsFound.setAttribute(
+ "ignoredAlertsFound", Integer.toString(ignoredAlerts.size()));
+ for (Alert alert : ignoredAlerts) {
+ createAlertXMLElements(ignoredAlertsFound, alert);
+ }
+ alertsDocument.getRootElement().addContent(ignoredAlertsFound);
+ }
+
+ writeAlertsToFile(outputFile, alertsDocument);
+ }
+
+ private static void writeAlertsToFile(File outputFile, Document doc) throws IOException {
+
+ XMLOutputter xmlOutput = new XMLOutputter();
+
+ xmlOutput.setFormat(Format.getPrettyFormat());
+ try (OutputStream os = Files.newOutputStream(outputFile.toPath())) {
+ xmlOutput.output(doc, os);
+ System.out.println("alert xml report saved to: " + outputFile.getAbsolutePath());
+ }
+ }
+
+ private static void createAlertXMLElements(Element alertsFound, Alert alert) {
+ Element alertElement = new Element("alert");
+ if (alert.getName() != null) {
+ alertElement.setAttribute("name", alert.getName());
+ // TODO Remove once alert attribute is no longer supported.
+ alertElement.setAttribute("alert", alert.getName());
+ }
+ if (alert.getRisk() != null) alertElement.setAttribute("risk", alert.getRisk().name());
+ if (alert.getUrl() != null)
+ alertElement.setAttribute("confidence", alert.getConfidence().name());
+ if (alert.getUrl() != null) alertElement.setAttribute("url", alert.getUrl());
+ if (alert.getParam() != null) alertElement.setAttribute("param", alert.getParam());
+ if (alert.getOther() != null) alertElement.setAttribute("other", alert.getOther());
+ if (alert.getAttack() != null) alertElement.setAttribute("attack", alert.getAttack());
+ if (alert.getDescription() != null)
+ alertElement.setAttribute("description", alert.getDescription());
+ if (alert.getSolution() != null) alertElement.setAttribute("solution", alert.getSolution());
+ if (alert.getReference() != null)
+ alertElement.setAttribute("reference", alert.getReference());
+ alertsFound.addContent(alertElement);
+ }
+
+ public static List getAlertsFromFile(File file, String alertType)
+ throws JDOMException, IOException {
+ List alerts = new ArrayList<>();
+ SAXBuilder parser = new SAXBuilder();
+ Document alertsDoc = parser.build(file);
+ @SuppressWarnings("unchecked")
+ List alertElements = alertsDoc.getRootElement().getChildren(alertType);
+ for (Element element : alertElements) {
+ String name = element.getAttributeValue("name");
+ if (name == null) {
+ // TODO Remove once alert attribute is no longer supported.
+ name = element.getAttributeValue("alert");
+ }
+ Alert alert =
+ new Alert(
+ name,
+ element.getAttributeValue("url"),
+ element.getAttributeValue("risk"),
+ element.getAttributeValue("confidence"),
+ element.getAttributeValue("param"),
+ element.getAttributeValue("other"));
+ alerts.add(alert);
+ }
+ return alerts;
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponse.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponse.java
index 71add5d..9db5608 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponse.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponse.java
@@ -1,40 +1,40 @@
/*
* Zed Attack Proxy (ZAP) and its related class files.
- *
+ *
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package org.zaproxy.clientapi.core;
-
public abstract class ApiResponse {
- private String name = null;
-
- public ApiResponse(String name) {
- super();
- this.name = name;
- }
+ private String name = null;
- public String getName() {
- return name;
- }
+ public ApiResponse(String name) {
+ super();
+ this.name = name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public String getName() {
+ return name;
+ }
- public abstract String toString(int indent);
+ public void setName(String name) {
+ this.name = name;
+ }
+ public abstract String toString(int indent);
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseElement.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseElement.java
index 5ccdd8b..44a8eca 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseElement.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseElement.java
@@ -1,67 +1,72 @@
/*
* Zed Attack Proxy (ZAP) and its related class files.
- *
+ *
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package org.zaproxy.clientapi.core;
import org.w3c.dom.Node;
public class ApiResponseElement extends ApiResponse {
-
- public static ApiResponseElement OK = new ApiResponseElement("Result", "OK");
- public static ApiResponseElement FAIL = new ApiResponseElement("Result", "FAIL");
-
- private String value = null;
- public ApiResponseElement(String name) {
- super(name);
- }
+ public static ApiResponseElement OK = new ApiResponseElement("Result", "OK");
+ public static ApiResponseElement FAIL = new ApiResponseElement("Result", "FAIL");
- public ApiResponseElement(String name, String value) {
- super(name);
- this.value = value;
- }
+ private String value = null;
- public ApiResponseElement(Node node, ApiResponse template) {
- super(node.getNodeName());
- this.value = node.getTextContent();
+ public ApiResponseElement(String name) {
+ super(name);
+ }
- }
+ public ApiResponseElement(String name, String value) {
+ super(name);
+ this.value = value;
+ }
- public ApiResponseElement(Node node) {
- super(node.getNodeName());
- this.value = node.getTextContent();
- }
+ public ApiResponseElement(Node node, ApiResponse template) {
+ super(node.getNodeName());
+ this.value = node.getTextContent();
+ }
- public String getValue() {
- return value;
- }
+ public ApiResponseElement(Node node) {
+ super(node.getNodeName());
+ this.value = node.getTextContent();
+ }
- @Override
- public String toString(int indent) {
- StringBuilder sb = new StringBuilder();
- for (int i=0 ; i < indent; i++) {
- sb.append("\t");
- }
- sb.append("ApiResponseElement ");
- sb.append(this.getName());
- sb.append(" = " );
- sb.append(this.getValue());
- sb.append("\n");
- return sb.toString();
- }
+ public String getValue() {
+ return value;
+ }
+ @Override
+ public String toString(int indent) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < indent; i++) {
+ sb.append("\t");
+ }
+ sb.append("ApiResponseElement ");
+ sb.append(this.getName());
+ sb.append(" = ");
+ sb.append(this.getValue());
+ sb.append("\n");
+ return sb.toString();
+ }
+
+ @Override
+ public String toString() {
+ return getValue();
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseFactory.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseFactory.java
index 20df241..03fd374 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseFactory.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseFactory.java
@@ -1,38 +1,55 @@
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package org.zaproxy.clientapi.core;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public final class ApiResponseFactory {
-
- private ApiResponseFactory() {
- }
-
- public static ApiResponse getResponse(Node node) throws ClientApiException {
- if (node == null) {
- throw new ClientApiException("Null node");
- }
- Node typeNode = node.getAttributes().getNamedItem("type");
- if (typeNode != null) {
- String type = typeNode.getNodeValue();
- if ("list".equals(type)) {
- return new ApiResponseList(node);
- }
- if ("set".equals(type)) {
- return new ApiResponseSet(node);
- }
- if ("exception".equals(type)) {
- NamedNodeMap atts = node.getAttributes();
- String code = atts.getNamedItem("code").getNodeValue();
- String detail = null;
- if (atts.getNamedItem("detail") != null) {
- detail = atts.getNamedItem("detail").getNodeValue();
- }
- throw new ClientApiException(node.getTextContent(), code, detail);
- }
- }
- return new ApiResponseElement(node);
- }
+ private ApiResponseFactory() {}
+ public static ApiResponse getResponse(Node node) throws ClientApiException {
+ if (node == null) {
+ throw new ClientApiException("Null node");
+ }
+ Node typeNode = node.getAttributes().getNamedItem("type");
+ if (typeNode != null) {
+ String type = typeNode.getNodeValue();
+ if ("list".equals(type)) {
+ return new ApiResponseList(node);
+ }
+ if ("set".equals(type)) {
+ return new ApiResponseSet(node);
+ }
+ if ("exception".equals(type)) {
+ NamedNodeMap atts = node.getAttributes();
+
+ String code = atts.getNamedItem("code").getNodeValue();
+ String detail = null;
+ if (atts.getNamedItem("detail") != null) {
+ detail = atts.getNamedItem("detail").getNodeValue();
+ }
+ throw new ClientApiException(node.getTextContent(), code, detail);
+ }
+ }
+ return new ApiResponseElement(node);
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseList.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseList.java
index 6bbbf38..d69cb5e 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseList.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseList.java
@@ -1,113 +1,115 @@
/*
* Zed Attack Proxy (ZAP) and its related class files.
- *
+ *
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package org.zaproxy.clientapi.core;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
-
import org.w3c.dom.Node;
public class ApiResponseList extends ApiResponse {
-
- private List list = null;
- public ApiResponseList(String name) {
- super(name);
- this.list = new ArrayList();
- }
+ private List list = null;
+
+ public ApiResponseList(String name) {
+ super(name);
+ this.list = new ArrayList<>();
+ }
+
+ public ApiResponseList(Node node) throws ClientApiException {
+ this(node.getNodeName());
+ Node child = node.getFirstChild();
+ while (child != null) {
+ addItemImpl(ApiResponseFactory.getResponse(child));
+ child = child.getNextSibling();
+ }
+ }
+
+ public ApiResponseList(Node node, ApiResponseList template) throws ClientApiException {
+ super(node.getNodeName());
+ try {
+ this.list = new ArrayList<>();
+ Class extends ApiResponse> clazz = template.getItemsClass();
+ if (clazz != null) {
+
+ Node child = node.getFirstChild();
+ while (child != null) {
+ Constructor extends ApiResponse> cons =
+ clazz.getConstructor(Node.class, ApiResponse.class);
+ addItemImpl(cons.newInstance(child, template.list.get(0)));
+ child = child.getNextSibling();
+ }
+ }
+ } catch (Exception e) {
+ throw new ClientApiException(e);
+ }
+ }
- public ApiResponseList(Node node)
- throws ClientApiException {
- this(node.getNodeName());
- Node child = node.getFirstChild();
- while (child != null) {
- this.addItem(ApiResponseFactory.getResponse(child));
- child = child.getNextSibling();
- }
- }
+ public ApiResponseList(String name, ApiResponse[] array) {
+ super(name);
+ this.list = new ArrayList<>();
+ for (ApiResponse resp : array) {
+ list.add(resp);
+ }
+ }
- public ApiResponseList(Node node, ApiResponseList template)
- throws ClientApiException {
- super(node.getNodeName());
- try {
- this.list = new ArrayList();
- Class extends ApiResponse> clazz = template.getItemsClass();
- if (clazz != null) {
+ public ApiResponseList(String name, List list) {
+ super(name);
+ this.list = list;
+ }
- Node child = node.getFirstChild();
- while (child != null) {
- Constructor extends ApiResponse> cons = clazz.getConstructor(Node.class, ApiResponse.class);
- this.addItem(cons.newInstance(child, template.list.get(0)));
- child = child.getNextSibling();
- }
- }
- } catch (Exception e) {
- throw new ClientApiException(e);
- }
- }
+ public void addItem(ApiResponse item) {
+ addItemImpl(item);
+ }
- public ApiResponseList(String name, ApiResponse[] array) {
- super(name);
- this.list = new ArrayList();
- for (ApiResponse resp: array) {
- list.add(resp);
- }
- }
+ private void addItemImpl(ApiResponse item) {
+ list.add(item);
+ }
- public ApiResponseList(String name, List list) {
- super(name);
- this.list = list;
- }
-
- public void addItem(ApiResponse item) {
- this.list.add(item);
- }
-
- public List getItems() {
- return this.list;
- }
-
- public Class extends ApiResponse> getItemsClass() {
- if (this.list == null || this.list.size() == 0) {
- return null;
- }
- return this.list.get(0).getClass();
- }
+ public List getItems() {
+ return this.list;
+ }
- @Override
- public String toString(int indent) {
- StringBuilder sb = new StringBuilder();
- for (int i=0 ; i < indent; i++) {
- sb.append("\t");
- }
- sb.append("ApiResponseList ");
- sb.append(this.getName());
- sb.append(" : [\n");
- for (ApiResponse resp: this.list) {
- sb.append(resp.toString(indent+1));
- }
- for (int i=0 ; i < indent; i++) {
- sb.append("\t");
- }
- sb.append("]\n");
- return sb.toString();
- }
+ public Class extends ApiResponse> getItemsClass() {
+ if (this.list == null || this.list.size() == 0) {
+ return null;
+ }
+ return this.list.get(0).getClass();
+ }
-
+ @Override
+ public String toString(int indent) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < indent; i++) {
+ sb.append("\t");
+ }
+ sb.append("ApiResponseList ");
+ sb.append(this.getName());
+ sb.append(" : [\n");
+ for (ApiResponse resp : this.list) {
+ sb.append(resp.toString(indent + 1));
+ }
+ for (int i = 0; i < indent; i++) {
+ sb.append("\t");
+ }
+ sb.append("]\n");
+ return sb.toString();
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseSet.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseSet.java
index 1e2ebdb..c3dd2c8 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseSet.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ApiResponseSet.java
@@ -1,19 +1,21 @@
/*
* Zed Attack Proxy (ZAP) and its related class files.
- *
+ *
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package org.zaproxy.clientapi.core;
@@ -23,148 +25,173 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
import org.w3c.dom.Node;
public class ApiResponseSet extends ApiResponse {
-
- private String[] attributes = null;
- private final Map valuesMap;
- /**
- * Constructs an {@code ApiResponseSet} with the given name and attributes.
- *
- * @param name the name of the API response
- * @param attributes the attributes
- * @deprecated (TODO add version) Unused, there's no replacement.
- */
- @Deprecated
- public ApiResponseSet(String name, String[] attributes) {
- super(name);
- this.attributes = attributes;
- this.valuesMap = Collections.emptyMap();
- }
+ private String[] attributes = null;
+ private final Map valuesMap;
+
+ /**
+ * Constructs an {@code ApiResponseSet} with the given name and attributes.
+ *
+ * @param name the name of the API response
+ * @param attributes the attributes
+ * @deprecated (1.1.0) Unused, there's no replacement.
+ */
+ @Deprecated
+ public ApiResponseSet(String name, String[] attributes) {
+ super(name);
+ this.attributes = attributes;
+ this.valuesMap = Collections.emptyMap();
+ }
+
+ public ApiResponseSet(String name, Map values) {
+ super(name);
+ this.valuesMap = Collections.unmodifiableMap(new HashMap<>(values));
+ }
- public ApiResponseSet(String name, Map values) {
- super(name);
- this.valuesMap = Collections.unmodifiableMap(new HashMap<>(values));
- }
+ public ApiResponseSet(Node node) throws ClientApiException {
+ super(node.getNodeName());
+ Node child = node.getFirstChild();
+ Map values = new HashMap<>();
+ while (child != null) {
+ ApiResponse elem = ApiResponseFactory.getResponse(child);
+ values.put(elem.getName(), elem);
+ child = child.getNextSibling();
+ }
+ this.valuesMap = Collections.unmodifiableMap(values);
+ }
- public ApiResponseSet(Node node) throws ClientApiException {
- super(node.getNodeName());
- Node child = node.getFirstChild();
- Map values = new HashMap<>();
- while (child != null) {
- ApiResponseElement elem = (ApiResponseElement) ApiResponseFactory.getResponse(child);
- values.put(elem.getName(), elem.getValue());
- child = child.getNextSibling();
- }
- this.valuesMap = Collections.unmodifiableMap(values);
- }
+ /**
+ * Gets the attributes.
+ *
+ * @return the attributes, might be {@code null}.
+ * @deprecated (1.1.0) Unused, there's no replacement.
+ * @see #getValues()
+ */
+ @Deprecated
+ public String[] getAttributes() {
+ return attributes;
+ }
- /**
- * Gets the attributes.
- *
- * @return the attributes, might be {@code null}.
- * @deprecated (TODO add version) Unused, there's no replacement.
- * @see #getValues()
- */
- @Deprecated
- public String[] getAttributes() {
- return attributes;
- }
-
- /**
- * Gets the value for the given {@code key}.
- *
- * @param key the key of the value
- * @return the value, or {@code null} if no value exists for the given {@code key}.
- * @deprecated (TODO add version) Use {@link #getValue(String)} instead.
- */
- @Deprecated
- public String getAttribute(String key) {
- return getValue(key);
- }
+ /**
+ * Gets the value for the given {@code key}.
+ *
+ * @param key the key of the value
+ * @return the value, or {@code null} if no value exists for the given {@code key}.
+ * @deprecated (1.1.0) Use {@link #getStringValue(String)} or {@link #getValue(String)} instead.
+ */
+ @Deprecated
+ public String getAttribute(String key) {
+ return getStringValue(key);
+ }
- /**
- * Gets the value for the given {@code key}.
- *
- * @param key the key of the value
- * @return the value, or {@code null} if no value exists for the given {@code key}.
- * @since TODO add version
- * @see #getKeys()
- */
- public String getValue(String key) {
- return valuesMap.get(key);
- }
+ /**
+ * Gets the value for the given {@code key}.
+ *
+ * @param key the key of the value
+ * @return the value, or {@code null} if no value exists for the given {@code key}.
+ * @since 1.1.0
+ * @see #getKeys()
+ * @see #getStringValue(String)
+ */
+ public ApiResponse getValue(String key) {
+ return valuesMap.get(key);
+ }
- /**
- * Gets a {@code Map} with the keys and values.
- *
- * The returned {@code Map} is unmodifiable, any attempt to modify it will result in an
- * {@code UnsupportedOperationException}.
- *
- * @return the map with the keys/values, never {@code null}.
- * @since TODO add version
- */
- public Map getValuesMap() {
- return valuesMap;
- }
+ /**
+ * Gets the value for the given {@code key} as {@code String}.
+ *
+ * For {@link ApiResponseElement}s it returns {@link ApiResponseElement#getValue() its
+ * value}, for other {@link ApiResponse} types it returns the conversion to {@code String}.
+ *
+ * @param key the key of the value
+ * @return the value, or {@code null} if no value exists for the given {@code key}.
+ * @since 1.1.0
+ * @see #getKeys()
+ * @see #getValue(String)
+ */
+ public String getStringValue(String key) {
+ ApiResponse value = valuesMap.get(key);
+ if (value instanceof ApiResponseElement) {
+ return ((ApiResponseElement) value).getValue();
+ }
+ return value != null ? value.toString() : null;
+ }
- /**
- * Gets the keys of the values.
- *
- * The returned {@code Set} is unmodifiable, any attempt to modify it will result in an
- * {@code UnsupportedOperationException}.
- *
- * @return the keys, never {@code null}.
- * @since TODO add version
- * @see #getValue(String)
- * @see #getValues()
- * @see #getValuesMap()
- */
- public Set getKeys() {
- return valuesMap.keySet();
- }
+ /**
+ * Gets a {@code Map} with the keys and values.
+ *
+ * The returned {@code Map} is unmodifiable, any attempt to modify it will result in an
+ * {@code UnsupportedOperationException}.
+ *
+ * @return the map with the keys/values, never {@code null}.
+ * @since 1.1.0
+ */
+ public Map getValuesMap() {
+ return valuesMap;
+ }
- /**
- * Gets the values.
- *
- * The returned {@code Collection} is unmodifiable, any attempt to modify it will result in an
- * {@code UnsupportedOperationException}.
- *
- * @return the values, never {@code null}.
- * @since TODO add version
- * @see #getValue(String)
- */
- public Collection getValues() {
- return valuesMap.values();
- }
+ /**
+ * Gets the keys of the values.
+ *
+ * The returned {@code Set} is unmodifiable, any attempt to modify it will result in an
+ * {@code UnsupportedOperationException}.
+ *
+ * @return the keys, never {@code null}.
+ * @since 1.1.0
+ * @see #getValue(String)
+ * @see #getStringValue(String)
+ * @see #getValues()
+ * @see #getValuesMap()
+ */
+ public Set getKeys() {
+ return valuesMap.keySet();
+ }
- @Override
- public String toString(int indent) {
- StringBuilder sb = new StringBuilder();
- for (int i=0 ; i < indent; i++) {
- sb.append("\t");
- }
- sb.append("ApiResponseSet ");
- sb.append(this.getName());
- sb.append(" : [\n");
- for (Entry val : valuesMap.entrySet()) {
- for (int i=0 ; i < indent+1; i++) {
- sb.append("\t");
- }
- sb.append(val.getKey());
- sb.append(" = ");
- sb.append(val.getValue());
- sb.append("\n");
- }
- for (int i=0 ; i < indent; i++) {
- sb.append("\t");
- }
- sb.append("]\n");
- return sb.toString();
- }
+ /**
+ * Gets the values.
+ *
+ * The returned {@code Collection} is unmodifiable, any attempt to modify it will result in
+ * an {@code UnsupportedOperationException}.
+ *
+ * @return the values, never {@code null}.
+ * @since 1.1.0
+ * @see #getValue(String)
+ * @see #getStringValue(String)
+ */
+ public Collection getValues() {
+ return valuesMap.values();
+ }
-
+ @Override
+ public String toString(int indent) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < indent; i++) {
+ sb.append("\t");
+ }
+ sb.append("ApiResponseSet ");
+ sb.append(this.getName());
+ sb.append(" : [\n");
+ for (Entry val : valuesMap.entrySet()) {
+ for (int i = 0; i < indent + 1; i++) {
+ sb.append("\t");
+ }
+ sb.append(val.getKey());
+ sb.append(" = ");
+ if (val.getValue() instanceof ApiResponseElement) {
+ sb.append(val.getValue());
+ } else {
+ sb.append('\n');
+ sb.append(val.getValue().toString(indent + 2));
+ }
+ sb.append("\n");
+ }
+ for (int i = 0; i < indent; i++) {
+ sb.append("\t");
+ }
+ sb.append("]\n");
+ return sb.toString();
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApi.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApi.java
index 494b3f1..e57e7a7 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApi.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApi.java
@@ -1,507 +1,889 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2011 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.core;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.MalformedURLException;
-import java.net.Proxy;
-import java.net.Socket;
-import java.net.SocketTimeoutException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.w3c.dom.Document;
-import org.zaproxy.clientapi.core.Alert.Confidence;
-import org.zaproxy.clientapi.core.Alert.Risk;
-import org.zaproxy.clientapi.gen.Acsrf;
-import org.zaproxy.clientapi.gen.AjaxSpider;
-import org.zaproxy.clientapi.gen.Ascan;
-import org.zaproxy.clientapi.gen.Authentication;
-import org.zaproxy.clientapi.gen.Authorization;
-import org.zaproxy.clientapi.gen.Autoupdate;
-import org.zaproxy.clientapi.gen.Break;
-import org.zaproxy.clientapi.gen.Context;
-import org.zaproxy.clientapi.gen.Core;
-import org.zaproxy.clientapi.gen.ForcedUser;
-import org.zaproxy.clientapi.gen.HttpSessions;
-import org.zaproxy.clientapi.gen.ImportLogFiles;
-import org.zaproxy.clientapi.gen.Params;
-import org.zaproxy.clientapi.gen.Pnh;
-import org.zaproxy.clientapi.gen.Pscan;
-import org.zaproxy.clientapi.gen.Reveal;
-import org.zaproxy.clientapi.gen.Script;
-import org.zaproxy.clientapi.gen.Search;
-import org.zaproxy.clientapi.gen.Selenium;
-import org.zaproxy.clientapi.gen.SessionManagement;
-import org.zaproxy.clientapi.gen.Spider;
-import org.zaproxy.clientapi.gen.Stats;
-import org.zaproxy.clientapi.gen.Users;
-
-public class ClientApi {
-
- private static final int DEFAULT_CONNECTION_POOLING_IN_MS = 1000;
-
- private Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8090));
- private boolean debug = false;
- private PrintStream debugStream = System.out;
-
- private final String zapAddress;
- private final int zapPort;
-
- // Note that any new API implementations added have to be added here manually
- public Acsrf acsrf = new Acsrf(this);
- public AjaxSpider ajaxSpider = new AjaxSpider(this);
- public Ascan ascan = new Ascan(this);
- public Authentication authentication = new Authentication(this);
- public Authorization authorization = new Authorization(this);
- public Autoupdate autoupdate = new Autoupdate(this);
- public Break brk = new Break(this);
- public Context context = new Context(this);
- public Core core = new Core(this);
- public ForcedUser forcedUser = new ForcedUser(this);
- public HttpSessions httpSessions = new HttpSessions(this);
- public ImportLogFiles logImportFiles = new ImportLogFiles(this);
- public Params params = new Params(this);
- public Pnh pnh = new Pnh(this);
- public Pscan pscan = new Pscan(this);
- public Reveal reveal = new Reveal(this);
- public Search search = new Search(this);
- public Script script = new Script(this);
- public Selenium selenium = new Selenium(this);
- public SessionManagement sessionManagement = new SessionManagement(this);
- public Spider spider = new Spider(this);
- public Stats stats = new Stats(this);
- public Users users = new Users(this);
-
- public ClientApi (String zapAddress, int zapPort) {
- this(zapAddress, zapPort, false);
- }
-
- public ClientApi (String zapAddress, int zapPort, boolean debug) {
- proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(zapAddress, zapPort));
- this.debug = debug;
- this.zapAddress = zapAddress;
- this.zapPort = zapPort;
- }
-
- public void setDebugStream(PrintStream debugStream) {
- this.debugStream = debugStream;
- }
-
- public void accessUrl (String url) throws ClientApiException {
- accessUrlViaProxy(proxy, url);
- }
-
- private int statusToInt(ApiResponse response) {
- return Integer.parseInt(((ApiResponseElement)response).getValue());
- }
-
- public void checkAlerts (List ignoreAlerts, List requireAlerts) throws ClientApiException {
- HashMap> results = checkForAlerts(ignoreAlerts, requireAlerts);
- verifyAlerts(results.get("requireAlerts"), results.get("reportAlerts"));
- }
-
- private void verifyAlerts(List requireAlerts, List reportAlerts) throws ClientApiException {
- StringBuilder sb = new StringBuilder();
- if (reportAlerts.size() > 0) {
- sb.append("Found ").append(reportAlerts.size()).append(" alerts\n");
- for (Alert alert: reportAlerts) {
- sb.append('\t');
- sb.append(alert.toString());
- sb.append('\n');
- }
- }
- if (requireAlerts != null && requireAlerts.size() > 0) {
- if (sb.length() > 0) {
- sb.append('\n');
- }
- sb.append("Not found ").append(requireAlerts.size()).append(" alerts\n");
- for (Alert alert: requireAlerts) {
- sb.append('\t');
- sb.append(alert.toString());
- sb.append('\n');
- }
- }
- if (sb.length() > 0) {
- if (debug) {
- debugStream.println("Failed: " + sb.toString());
- }
- throw new ClientApiException (sb.toString());
- }
- }
-
- public void checkAlerts(List ignoreAlerts, List requireAlerts, File outputFile) throws ClientApiException {
- HashMap> results = checkForAlerts(ignoreAlerts, requireAlerts);
- int alertsFound = results.get("reportAlerts").size();
- int alertsNotFound = results.get("requireAlerts").size();
- int alertsIgnored = results.get("ignoredAlerts").size();
- String resultsString = String.format("Alerts Found: %d, Alerts required but not found: %d, Alerts ignored: %d", alertsFound, alertsNotFound, alertsIgnored);
- try {
- AlertsFile.saveAlertsToFile(results.get("requireAlerts"), results.get("reportAlerts"), results.get("ignoredAlerts"), outputFile);
- } catch (Exception e) {
- throw new ClientApiException (e);
- }
- if (alertsFound>0 || alertsNotFound>0){
- throw new ClientApiException("Check Alerts Failed!\n"+resultsString);
- }else{
- if (debug) {
- debugStream.println("Check Alerts Passed!\n" + resultsString);
- }
- }
- }
-
- public List getAlerts(String baseUrl, int start, int count) throws ClientApiException {
- List alerts = new ArrayList();
- ApiResponse response = core.alerts(baseUrl, String.valueOf(start), String.valueOf(count));
- if (response != null && response instanceof ApiResponseList) {
- ApiResponseList alertList = (ApiResponseList)response;
- for (ApiResponse resp : alertList.getItems()) {
- ApiResponseSet alertSet = (ApiResponseSet)resp;
- alerts.add(new Alert(
- alertSet.getValue("alert"),
- alertSet.getValue("url"),
- Risk.valueOf(alertSet.getValue("risk")),
- Confidence.valueOf(alertSet.getValue("confidence")),
- alertSet.getValue("param"),
- alertSet.getValue("other"),
- alertSet.getValue("attack"),
- alertSet.getValue("description"),
- alertSet.getValue("reference"),
- alertSet.getValue("solution"),
- alertSet.getValue("evidence"),
- Integer.parseInt(alertSet.getValue("cweid")),
- Integer.parseInt(alertSet.getValue("wascid"))));
- }
- }
- return alerts;
- }
-
- private HashMap> checkForAlerts(List ignoreAlerts, List requireAlerts) throws ClientApiException {
- List reportAlerts = new ArrayList<>();
- List ignoredAlerts = new ArrayList<>();
- List alerts = getAlerts(null, -1, -1);
- for (Alert alert : alerts) {
- boolean ignore = false;
- if (ignoreAlerts != null) {
- for (Alert ignoreAlert : ignoreAlerts) {
- if (alert.matches(ignoreAlert)) {
- if (debug) {
- debugStream.println("Ignoring alert " + ignoreAlert);
- }
- ignoredAlerts.add(alert);
- ignore = true;
- break;
- }
- }
- }
- if (! ignore) {
- reportAlerts.add(alert);
- }
- if (requireAlerts != null) {
- for (Alert requireAlert : requireAlerts) {
- if (alert.matches(requireAlert)) {
- if (debug) {
- debugStream.println("Found alert " + alert);
- }
- requireAlerts.remove(requireAlert);
- // Remove it from the not-ignored list as well
- reportAlerts.remove(alert);
- break;
- }
- }
- }
- }
- HashMap> results = new HashMap<>();
- results.put("reportAlerts", reportAlerts);
- results.put("requireAlerts", requireAlerts);
- results.put("ignoredAlerts", ignoredAlerts);
- return results;
- }
-
- private void accessUrlViaProxy (Proxy proxy, String apiurl) throws ClientApiException {
- try {
- URL url = new URL(apiurl);
- if (debug) {
- debugStream.println("Open URL: " + apiurl);
- }
- HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
- uc.connect();
-
- BufferedReader in;
- try {
- in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
- String inputLine;
-
- while ((inputLine = in.readLine()) != null) {
- if (debug) {
- debugStream.println(inputLine);
- }
- }
- in.close();
-
- } catch (IOException e) {
- // Ignore
- if (debug) {
- debugStream.println("Ignoring exception " + e);
- }
- }
- } catch (Exception e) {
- throw new ClientApiException (e);
- }
- }
-
- public ApiResponse callApi (String component, String type, String method,
- Map params) throws ClientApiException {
- Document dom = this.callApiDom(component, type, method, params);
- return ApiResponseFactory.getResponse(dom.getFirstChild());
- }
-
- private Document callApiDom (String component, String type, String method,
- Map params) throws ClientApiException {
- try {
- URL url = buildZapRequestUrl("xml", component, type, method, params);
- if (debug) {
- debugStream.println("Open URL: " + url);
- }
- //get the factory
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- //Using factory get an instance of document builder
- DocumentBuilder db = dbf.newDocumentBuilder();
- //parse using builder to get DOM representation of the XML file
- return db.parse(getConnectionInputStream(url));
- } catch (Exception e) {
- throw new ClientApiException(e);
- }
- }
-
- private InputStream getConnectionInputStream(URL url) throws IOException {
- HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
- uc.connect();
- if (uc.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
- return uc.getErrorStream();
- }
- return uc.getInputStream();
- }
-
- public byte[] callApiOther (String component, String type, String method,
- Map params) throws ClientApiException {
- try {
- URL url = buildZapRequestUrl("other", component, type, method, params);
- if (debug) {
- debugStream.println("Open URL: " + url);
- }
- InputStream in = getConnectionInputStream(url);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buffer = new byte[8 * 1024];
- try {
- int bytesRead;
- while ((bytesRead = in.read(buffer)) != -1) {
- out.write(buffer, 0, bytesRead);
- }
- } finally {
- out.close();
- in.close();
- }
- return out.toByteArray();
-
- } catch (Exception e) {
- throw new ClientApiException(e);
- }
- }
-
- private static URL buildZapRequestUrl(
- String format,
- String component,
- String type,
- String method,
- Map params) throws MalformedURLException {
- StringBuilder sb = new StringBuilder();
- sb.append("http://zap/");
- sb.append(format);
- sb.append('/');
- sb.append(component);
- sb.append('/');
- sb.append(type);
- sb.append('/');
- sb.append(method);
- sb.append('/');
- if (params != null) {
- sb.append('?');
- for (Map.Entry p : params.entrySet()) {
- sb.append(encodeQueryParam(p.getKey()));
- sb.append('=');
- if (p.getValue() != null) {
- sb.append(encodeQueryParam(p.getValue()));
- }
- sb.append('&');
- }
- }
-
- return new URL(sb.toString());
- }
-
- private static String encodeQueryParam(String param) {
- try {
- return URLEncoder.encode(param, "UTF-8");
- } catch (UnsupportedEncodingException ignore) {
- // UTF-8 is a standard charset.
- }
- return param;
- }
-
- public void addExcludeFromContext(String apikey, String contextName, String regex) throws Exception {
- context.excludeFromContext(apikey, contextName, regex);
- }
-
- public void addIncludeInContext(String apikey, String contextName, String regex) throws Exception {
- context.includeInContext(apikey, contextName, regex);
- }
-
- public void includeOneMatchingNodeInContext(String apikey, String contextName, String regex) throws Exception {
- List sessionUrls = getSessionUrls();
- boolean foundOneMatch = false;
- for (String sessionUrl : sessionUrls){
- if (sessionUrl.matches(regex)){
- if (foundOneMatch){
- addExcludeFromContext(apikey, contextName, sessionUrl);
- } else {
- foundOneMatch = true;
- }
- }
- }
- if(!foundOneMatch){
- throw new Exception("Unexpected result: No url found in site tree matching regex " + regex);
- }
-
- }
-
- private List getSessionUrls() throws Exception {
- List sessionUrls = new ArrayList<>();
- ApiResponse response = core.urls();
- if (response != null && response instanceof ApiResponseList) {
- ApiResponseElement urlList = (ApiResponseElement) ((ApiResponseList) response).getItems().get(0);
- for (ApiResponse element: ((ApiResponseList) response).getItems()){
- URL url = new URL(((ApiResponseElement)element).getValue());
- sessionUrls.add(url.getProtocol()+"://"+url.getHost()+url.getPath());
- }
- System.out.println(urlList);
- }
- return sessionUrls;
- }
-
- public void activeScanSiteInScope(String apikey, String url) throws Exception {
- ascan.scan(apikey, url, "true", "true", "", "", "");
- // Poll until spider finished
- int status = 0;
- while ( status < 100) {
- status = statusToInt(ascan.status(""));
- if(debug){
- String format = "Scanning %s Progress: %d%%";
- System.out.println(String.format(format, url, status));
- }try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // Ignore
- }
- }
- }
-
- /**
- * Convenience method to wait for ZAP to be ready to receive API calls, when started programmatically.
- *
- * It attempts to establish a connection to ZAP's proxy, in the given time, throwing an exception if the connection is not
- * successful. The connection attempts might be polled in one second interval.
- *
- * @param timeoutInSeconds the (maximum) number of seconds to wait for ZAP to start
- * @throws ClientApiException if the timeout was reached or if the thread was interrupted while waiting
- * @see #waitForSuccessfulConnectionToZap(int, int)
- */
- public void waitForSuccessfulConnectionToZap(int timeoutInSeconds) throws ClientApiException {
- waitForSuccessfulConnectionToZap(timeoutInSeconds, DEFAULT_CONNECTION_POOLING_IN_MS);
- }
-
- /**
- * Convenience method to wait for ZAP to be ready to receive API calls, when started programmatically.
- *
- * It attempts to establish a connection to ZAP's proxy, in the given time, throwing an exception if the connection is not
- * successful. The connection attempts are done with the given polling interval.
- *
- * @param timeoutInSeconds the (maximum) number of seconds to wait for ZAP to start
- * @param pollingIntervalInMs the interval, in milliseconds, for connection polling
- * @throws ClientApiException if the timeout was reached or if the thread was interrupted while waiting.
- * @throws IllegalArgumentException if the interval for connection polling is negative.
- * @see #waitForSuccessfulConnectionToZap(int)
- */
- public void waitForSuccessfulConnectionToZap(int timeoutInSeconds, int pollingIntervalInMs) throws ClientApiException {
- int timeoutInMs = (int) TimeUnit.SECONDS.toMillis(timeoutInSeconds);
- int connectionTimeoutInMs = timeoutInMs;
- boolean connectionSuccessful = false;
- long startTime = System.currentTimeMillis();
- do {
- try (Socket socket = new Socket()) {
- try {
- socket.connect(new InetSocketAddress(zapAddress, zapPort), connectionTimeoutInMs);
- connectionSuccessful = true;
- } catch (SocketTimeoutException ignore) {
- throw newTimeoutConnectionToZap(timeoutInSeconds);
- } catch (IOException ignore) {
- // and keep trying but wait some time first...
- try {
- Thread.sleep(pollingIntervalInMs);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new ClientApiException(
- "The ClientApi was interrupted while sleeping between connection polling.",
- e);
- }
-
- long ellapsedTime = System.currentTimeMillis() - startTime;
- if (ellapsedTime >= timeoutInMs) {
- throw newTimeoutConnectionToZap(timeoutInSeconds);
- }
- connectionTimeoutInMs = (int) (timeoutInMs - ellapsedTime);
- }
- } catch (IOException ignore) {
- // the closing state doesn't matter.
- }
- } while (!connectionSuccessful);
- }
-
- private static ClientApiException newTimeoutConnectionToZap(int timeoutInSeconds) {
- return new ClientApiException("Unable to connect to ZAP's proxy after " + timeoutInSeconds + " seconds.");
- }
-}
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2011 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.core;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.Proxy;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.w3c.dom.Document;
+import org.zaproxy.clientapi.gen.AccessControl;
+import org.zaproxy.clientapi.gen.Acsrf;
+import org.zaproxy.clientapi.gen.AjaxSpider;
+import org.zaproxy.clientapi.gen.AlertFilter;
+import org.zaproxy.clientapi.gen.Ascan;
+import org.zaproxy.clientapi.gen.Authentication;
+import org.zaproxy.clientapi.gen.Authorization;
+import org.zaproxy.clientapi.gen.Automation;
+import org.zaproxy.clientapi.gen.Autoupdate;
+import org.zaproxy.clientapi.gen.Break;
+import org.zaproxy.clientapi.gen.Client;
+import org.zaproxy.clientapi.gen.ClientSpider;
+import org.zaproxy.clientapi.gen.Context;
+import org.zaproxy.clientapi.gen.Core;
+import org.zaproxy.clientapi.gen.Exim;
+import org.zaproxy.clientapi.gen.ForcedUser;
+import org.zaproxy.clientapi.gen.Graphql;
+import org.zaproxy.clientapi.gen.HttpSessions;
+import org.zaproxy.clientapi.gen.Network;
+import org.zaproxy.clientapi.gen.Oast;
+import org.zaproxy.clientapi.gen.Openapi;
+import org.zaproxy.clientapi.gen.Params;
+import org.zaproxy.clientapi.gen.Pnh;
+import org.zaproxy.clientapi.gen.Postman;
+import org.zaproxy.clientapi.gen.Pscan;
+import org.zaproxy.clientapi.gen.Replacer;
+import org.zaproxy.clientapi.gen.Reports;
+import org.zaproxy.clientapi.gen.Retest;
+import org.zaproxy.clientapi.gen.Reveal;
+import org.zaproxy.clientapi.gen.Revisit;
+import org.zaproxy.clientapi.gen.RuleConfig;
+import org.zaproxy.clientapi.gen.Script;
+import org.zaproxy.clientapi.gen.Search;
+import org.zaproxy.clientapi.gen.Selenium;
+import org.zaproxy.clientapi.gen.SessionManagement;
+import org.zaproxy.clientapi.gen.Soap;
+import org.zaproxy.clientapi.gen.Spider;
+import org.zaproxy.clientapi.gen.Stats;
+import org.zaproxy.clientapi.gen.Users;
+import org.zaproxy.clientapi.gen.Wappalyzer;
+import org.zaproxy.clientapi.gen.Websocket;
+
+@SuppressWarnings("this-escape")
+public class ClientApi {
+
+ private static final int DEFAULT_CONNECTION_POOLING_IN_MS = 1000;
+
+ private static final String ZAP_API_KEY_HEADER = "X-ZAP-API-Key";
+
+ private Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8090));
+ private boolean debug = false;
+ private PrintStream debugStream = System.out;
+
+ private final String zapAddress;
+ private final int zapPort;
+
+ private final String apiKey;
+
+ private DocumentBuilderFactory docBuilderFactory;
+
+ // Note that any new API implementations added have to be added here manually
+ public AccessControl accessControl = new AccessControl(this);
+ public Acsrf acsrf = new Acsrf(this);
+ public AjaxSpider ajaxSpider = new AjaxSpider(this);
+ public AlertFilter alertFilter = new AlertFilter(this);
+ public org.zaproxy.clientapi.gen.Alert alert = new org.zaproxy.clientapi.gen.Alert(this);
+ public Ascan ascan = new Ascan(this);
+ public Authentication authentication = new Authentication(this);
+ public Authorization authorization = new Authorization(this);
+ public Automation automation = new Automation(this);
+ public Autoupdate autoupdate = new Autoupdate(this);
+ public Break brk = new Break(this);
+ public Client client = new Client(this);
+ public ClientSpider clientSpider = new ClientSpider(this);
+ public Context context = new Context(this);
+ public Core core = new Core(this);
+ public Exim exim = new Exim(this);
+
+ @SuppressWarnings("removal")
+ public org.zaproxy.clientapi.gen.Exportreport exportreport =
+ new org.zaproxy.clientapi.gen.Exportreport(this);
+
+ public ForcedUser forcedUser = new ForcedUser(this);
+ public Graphql graphql = new Graphql(this);
+ public HttpSessions httpSessions = new HttpSessions(this);
+
+ @SuppressWarnings("removal")
+ public org.zaproxy.clientapi.gen.ImportLogFiles logImportFiles =
+ new org.zaproxy.clientapi.gen.ImportLogFiles(this);
+
+ @SuppressWarnings("removal")
+ public org.zaproxy.clientapi.gen.Importurls importurls =
+ new org.zaproxy.clientapi.gen.Importurls(this);
+
+ @SuppressWarnings("removal")
+ public org.zaproxy.clientapi.gen.LocalProxies localProxies =
+ new org.zaproxy.clientapi.gen.LocalProxies(this);
+
+ public Network network = new Network(this);
+ public Oast oast = new Oast(this);
+ public Openapi openapi = new Openapi(this);
+ public Params params = new Params(this);
+ public Pnh pnh = new Pnh(this);
+ public Postman postman = new Postman(this);
+ public Pscan pscan = new Pscan(this);
+ public Replacer replacer = new Replacer(this);
+ public Reports reports = new Reports(this);
+ public Retest retest = new Retest(this);
+ public Reveal reveal = new Reveal(this);
+ public Revisit revisit = new Revisit(this);
+ public RuleConfig ruleConfig = new RuleConfig(this);
+ public Search search = new Search(this);
+ public Script script = new Script(this);
+ public Selenium selenium = new Selenium(this);
+ public SessionManagement sessionManagement = new SessionManagement(this);
+ public Soap soap = new Soap(this);
+ public Spider spider = new Spider(this);
+ public Stats stats = new Stats(this);
+ public Users users = new Users(this);
+ public Wappalyzer wappalyzer = new Wappalyzer(this);
+ public Websocket websocket = new Websocket(this);
+
+ public ClientApi(String zapAddress, int zapPort) {
+ this(zapAddress, zapPort, false);
+ }
+
+ /**
+ * Constructs a {@code ClientApi} with the given ZAP address/port and with the given API key, to
+ * be sent with all API requests.
+ *
+ * @param zapAddress ZAP's address
+ * @param zapPort ZAP's listening port
+ * @param apiKey the ZAP API key, might be {@code null} or empty in which case is not used/sent.
+ * @since 1.1.0
+ */
+ public ClientApi(String zapAddress, int zapPort, String apiKey) {
+ this(zapAddress, zapPort, apiKey, false);
+ }
+
+ public ClientApi(String zapAddress, int zapPort, boolean debug) {
+ this(zapAddress, zapPort, null, debug);
+ }
+
+ /**
+ * Constructs a {@code ClientApi} with the given ZAP address/port and with the given API key, to
+ * be sent with all API requests. Also, sets whether or not client API debug information should
+ * be written to the {@link #setDebugStream(PrintStream) debug stream} (by default the standard
+ * output stream).
+ *
+ * @param zapAddress ZAP's address
+ * @param zapPort ZAP's listening port
+ * @param apiKey the ZAP API key, might be {@code null} or empty in which case is not used/sent.
+ * @param debug {@code true} if debug information should be written to debug stream, {@code
+ * false} otherwise.
+ * @since 1.1.0
+ */
+ public ClientApi(String zapAddress, int zapPort, String apiKey, boolean debug) {
+ proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(zapAddress, zapPort));
+ this.debug = debug;
+ this.zapAddress = zapAddress;
+ this.zapPort = zapPort;
+ this.apiKey = apiKey;
+ }
+
+ public void setDebugStream(PrintStream debugStream) {
+ this.debugStream = debugStream;
+ }
+
+ public void accessUrl(String url) throws ClientApiException {
+ accessUrlViaProxy(proxy, url);
+ }
+
+ private int statusToInt(ApiResponse response) {
+ return Integer.parseInt(((ApiResponseElement) response).getValue());
+ }
+
+ public void checkAlerts(List ignoreAlerts, List requireAlerts)
+ throws ClientApiException {
+ Map> results = checkForAlerts(ignoreAlerts, requireAlerts);
+ verifyAlerts(results.get("requireAlerts"), results.get("reportAlerts"));
+ }
+
+ private void verifyAlerts(List requireAlerts, List reportAlerts)
+ throws ClientApiException {
+ StringBuilder sb = new StringBuilder();
+ if (reportAlerts.size() > 0) {
+ sb.append("Found ").append(reportAlerts.size()).append(" alerts\n");
+ for (Alert alert : reportAlerts) {
+ sb.append('\t');
+ sb.append(alert.toString());
+ sb.append('\n');
+ }
+ }
+ if (requireAlerts != null && requireAlerts.size() > 0) {
+ if (sb.length() > 0) {
+ sb.append('\n');
+ }
+ sb.append("Not found ").append(requireAlerts.size()).append(" alerts\n");
+ for (Alert alert : requireAlerts) {
+ sb.append('\t');
+ sb.append(alert.toString());
+ sb.append('\n');
+ }
+ }
+ if (sb.length() > 0) {
+ if (debug) {
+ debugStream.println("Failed: " + sb.toString());
+ }
+ throw new ClientApiException(sb.toString());
+ }
+ }
+
+ public void checkAlerts(List ignoreAlerts, List requireAlerts, File outputFile)
+ throws ClientApiException {
+ Map> results = checkForAlerts(ignoreAlerts, requireAlerts);
+ int alertsFound = results.get("reportAlerts").size();
+ int alertsNotFound = results.get("requireAlerts").size();
+ int alertsIgnored = results.get("ignoredAlerts").size();
+ String resultsString =
+ String.format(
+ "Alerts Found: %d, Alerts required but not found: %d, Alerts ignored: %d",
+ alertsFound, alertsNotFound, alertsIgnored);
+ try {
+ AlertsFile.saveAlertsToFile(
+ results.get("requireAlerts"),
+ results.get("reportAlerts"),
+ results.get("ignoredAlerts"),
+ outputFile);
+ } catch (Exception e) {
+ throw new ClientApiException("Failed to save the alerts:", e);
+ }
+ if (alertsFound > 0 || alertsNotFound > 0) {
+ throw new ClientApiException("Check Alerts Failed!\n" + resultsString);
+ } else {
+ if (debug) {
+ debugStream.println("Check Alerts Passed!\n" + resultsString);
+ }
+ }
+ }
+
+ public List getAlerts(String baseUrl, int start, int count) throws ClientApiException {
+ List alerts = new ArrayList<>();
+ ApiResponse response =
+ alert.alerts(baseUrl, String.valueOf(start), String.valueOf(count), null);
+ if (response != null && response instanceof ApiResponseList) {
+ ApiResponseList alertList = (ApiResponseList) response;
+ for (ApiResponse resp : alertList.getItems()) {
+ alerts.add(new Alert((ApiResponseSet) resp));
+ }
+ }
+ return alerts;
+ }
+
+ private Map> checkForAlerts(
+ List ignoreAlerts, List requireAlerts) throws ClientApiException {
+ List reportAlerts = new ArrayList<>();
+ List ignoredAlerts = new ArrayList<>();
+ List alerts = getAlerts(null, -1, -1);
+ for (Alert alert : alerts) {
+ boolean ignore = false;
+ if (ignoreAlerts != null) {
+ for (Alert ignoreAlert : ignoreAlerts) {
+ if (alert.matches(ignoreAlert)) {
+ if (debug) {
+ debugStream.println("Ignoring alert " + ignoreAlert);
+ }
+ ignoredAlerts.add(alert);
+ ignore = true;
+ break;
+ }
+ }
+ }
+ if (!ignore) {
+ reportAlerts.add(alert);
+ }
+ if (requireAlerts != null) {
+ for (Alert requireAlert : requireAlerts) {
+ if (alert.matches(requireAlert)) {
+ if (debug) {
+ debugStream.println("Found alert " + alert);
+ }
+ requireAlerts.remove(requireAlert);
+ // Remove it from the not-ignored list as well
+ reportAlerts.remove(alert);
+ break;
+ }
+ }
+ }
+ }
+ HashMap> results = new HashMap<>();
+ results.put("reportAlerts", reportAlerts);
+ results.put("requireAlerts", requireAlerts);
+ results.put("ignoredAlerts", ignoredAlerts);
+ return results;
+ }
+
+ private void accessUrlViaProxy(Proxy proxy, String apiurl) throws ClientApiException {
+ try {
+ URL url = createUrl(apiurl);
+ if (debug) {
+ debugStream.println("Open URL: " + apiurl);
+ }
+ HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
+ uc.connect();
+
+ try (BufferedReader in =
+ new BufferedReader(
+ new InputStreamReader(uc.getInputStream(), StandardCharsets.UTF_8))) {
+ String inputLine;
+
+ while ((inputLine = in.readLine()) != null) {
+ if (debug) {
+ debugStream.println(inputLine);
+ }
+ }
+
+ } catch (IOException e) {
+ // Ignore
+ if (debug) {
+ debugStream.println("Ignoring exception " + e);
+ }
+ }
+ } catch (Exception e) {
+ throw new ClientApiException(e);
+ }
+ }
+
+ private static URL createUrl(String value) throws MalformedURLException, URISyntaxException {
+ return new URI(value).toURL();
+ }
+
+ public ApiResponse callApi(
+ String component, String type, String method, Map params)
+ throws ClientApiException {
+ return callApi(HttpRequest.GET_METHOD, component, type, method, params);
+ }
+
+ public ApiResponse callApi(
+ String requestMethod,
+ String component,
+ String type,
+ String method,
+ Map params)
+ throws ClientApiException {
+ Document dom = this.callApiDom(requestMethod, component, type, method, params);
+ return ApiResponseFactory.getResponse(dom.getFirstChild());
+ }
+
+ private Document callApiDom(
+ String requestMethod,
+ String component,
+ String type,
+ String method,
+ Map params)
+ throws ClientApiException {
+ try {
+ HttpRequest request =
+ buildZapRequest(requestMethod, "xml", component, type, method, params);
+ if (debug) {
+ debugStream.println("Open URL: " + request.getRequestUri());
+ }
+ DocumentBuilder db = getDocumentBuilderFactory().newDocumentBuilder();
+ // parse using builder to get DOM representation of the XML file
+ return db.parse(getConnectionInputStream(request));
+ } catch (Exception e) {
+ throw new ClientApiException(e);
+ }
+ }
+
+ /**
+ * Gets the {@code DocumentBuilderFactory} instance with XML External Entity (XXE) processing
+ * disabled.
+ *
+ * @return the {@code DocumentBuilderFactory} instance with XXE processing disabled.
+ * @throws ParserConfigurationException if an error occurred while disabling XXE processing.
+ * @see DocumentBuilderFactory
+ */
+ private DocumentBuilderFactory getDocumentBuilderFactory() throws ParserConfigurationException {
+ if (docBuilderFactory == null) {
+ // Disable XXE processing, not required by default.
+ // https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ factory.setExpandEntityReferences(false);
+ docBuilderFactory = factory;
+ }
+ return docBuilderFactory;
+ }
+
+ private InputStream getConnectionInputStream(HttpRequest request) throws IOException {
+ HttpURLConnection uc = (HttpURLConnection) request.getRequestUri().openConnection(proxy);
+ uc.setUseCaches(false);
+ for (Entry header : request.getHeaders().entrySet()) {
+ uc.setRequestProperty(header.getKey(), header.getValue());
+ }
+ if (!isGetRequest(request.getMethod())) {
+ uc.setRequestMethod(request.getMethod());
+ String body = request.getBody();
+ if (body != null && !body.isEmpty()) {
+ uc.setDoOutput(true);
+ try (var os =
+ new OutputStreamWriter(uc.getOutputStream(), StandardCharsets.UTF_8)) {
+ os.write(request.getBody());
+ }
+ }
+ }
+ uc.connect();
+ if (uc.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
+ return uc.getErrorStream();
+ }
+ return uc.getInputStream();
+ }
+
+ public byte[] callApiOther(
+ String component, String type, String method, Map params)
+ throws ClientApiException {
+ return callApiOther(HttpRequest.GET_METHOD, component, type, method, params);
+ }
+
+ public byte[] callApiOther(
+ String requestMethod,
+ String component,
+ String type,
+ String method,
+ Map params)
+ throws ClientApiException {
+ return getBytes(requestMethod, "other", component, type, method, params);
+ }
+
+ public String callApiJson(
+ String component, String type, String method, Map params)
+ throws ClientApiException {
+ byte[] json = getBytes(HttpRequest.GET_METHOD, "JSON", component, type, method, params);
+ return new String(json, StandardCharsets.UTF_8);
+ }
+
+ private byte[] getBytes(
+ String requestMethod,
+ String format,
+ String component,
+ String type,
+ String method,
+ Map params)
+ throws ClientApiException {
+ try {
+ HttpRequest request =
+ buildZapRequest(requestMethod, format, component, type, method, params);
+ if (debug) {
+ debugStream.println("Open URL: " + request.getRequestUri());
+ }
+ InputStream in = getConnectionInputStream(request);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[8 * 1024];
+ try {
+ int bytesRead;
+ while ((bytesRead = in.read(buffer)) != -1) {
+ out.write(buffer, 0, bytesRead);
+ }
+ } finally {
+ out.close();
+ in.close();
+ }
+ return out.toByteArray();
+
+ } catch (Exception e) {
+ throw new ClientApiException(e);
+ }
+ }
+
+ /**
+ * Builds a request for the ZAP API with the given data.
+ *
+ * As the API client proxies through ZAP the built API requests use a specific domain, {@code
+ * zap}, to ensure that they are always handled by ZAP (and not forward).
+ *
+ * @param requestMethod the HTTP request method.
+ * @param format the desired format of the API response (e.g. XML, JSON, other).
+ * @param component the API component (e.g. core, spider).
+ * @param type the type of the API endpoint (e.g. action, view).
+ * @param method the name of the endpoint.
+ * @param params the parameters for the endpoint.
+ * @return the API request.
+ * @throws MalformedURLException if an error occurred while building the URL.
+ * @throws URISyntaxException if an error occurred while building the URL.
+ */
+ private HttpRequest buildZapRequest(
+ String requestMethod,
+ String format,
+ String component,
+ String type,
+ String method,
+ Map params)
+ throws MalformedURLException, URISyntaxException {
+ StringBuilder sb = new StringBuilder();
+ sb.append("http://zap/");
+ sb.append(format);
+ sb.append('/');
+ sb.append(component);
+ sb.append('/');
+ sb.append(type);
+ sb.append('/');
+ sb.append(method);
+ sb.append('/');
+ String body = null;
+ if (params != null) {
+ if (isGetRequest(requestMethod)) {
+ sb.append('?');
+ appendParams(params, sb);
+ } else {
+ body = appendParams(params, new StringBuilder()).toString();
+ }
+ }
+
+ HttpRequest request = new HttpRequest(requestMethod, createUrl(sb.toString()), body);
+ if (apiKey != null && !apiKey.isEmpty()) {
+ request.addHeader(ZAP_API_KEY_HEADER, apiKey);
+ }
+ return request;
+ }
+
+ private static boolean isGetRequest(String requestMethod) {
+ return HttpRequest.GET_METHOD.equals(requestMethod);
+ }
+
+ private static StringBuilder appendParams(Map params, StringBuilder sb) {
+ for (Map.Entry p : params.entrySet()) {
+ sb.append(encodeQueryParam(p.getKey()));
+ sb.append('=');
+ if (p.getValue() != null) {
+ sb.append(encodeQueryParam(p.getValue()));
+ }
+ sb.append('&');
+ }
+ return sb;
+ }
+
+ private static String encodeQueryParam(String param) {
+ try {
+ return URLEncoder.encode(param, "UTF-8");
+ } catch (UnsupportedEncodingException ignore) {
+ // UTF-8 is a standard charset.
+ }
+ return param;
+ }
+
+ /**
+ * Adds the given regular expression to the exclusion list of the given context.
+ *
+ * @param apiKey the API key, might be {@code null}.
+ * @param contextName the name of the context.
+ * @param regex the regular expression to add.
+ * @throws Exception if an error occurred while calling the API.
+ * @deprecated (1.1.0) Use {@link Context#excludeFromContext(String, String)} instead.
+ * @see #context
+ */
+ @Deprecated
+ public void addExcludeFromContext(String apiKey, String contextName, String regex)
+ throws Exception {
+ context.excludeFromContext(apiKey, contextName, regex);
+ }
+
+ /**
+ * Adds the given regular expression to the inclusion list of the given context.
+ *
+ * @param apiKey the API key, might be {@code null}.
+ * @param contextName the name of the context.
+ * @param regex the regular expression to add.
+ * @throws Exception if an error occurred while calling the API.
+ * @deprecated (1.1.0) Use {@link Context#includeInContext(String, String)} instead.
+ * @see #context
+ */
+ @Deprecated
+ public void addIncludeInContext(String apiKey, String contextName, String regex)
+ throws Exception {
+ context.includeInContext(apiKey, contextName, regex);
+ }
+
+ /**
+ * Includes just one of the nodes that match the given regular expression in the context with
+ * the given name.
+ *
+ * Nodes that do not match the regular expression are excluded.
+ *
+ * @param apiKey the API key, might be {@code null}.
+ * @param contextName the name of the context.
+ * @param regex the regular expression to match the node/URL.
+ * @throws Exception if an error occurred while calling the API.
+ * @deprecated (1.1.0) Use {@link #includeOneMatchingNodeInContext(String, String)} instead.
+ */
+ @Deprecated
+ public void includeOneMatchingNodeInContext(String apiKey, String contextName, String regex)
+ throws Exception {
+ List sessionUrls = getSessionUrls();
+ boolean foundOneMatch = false;
+ for (String sessionUrl : sessionUrls) {
+ if (sessionUrl.matches(regex)) {
+ if (foundOneMatch) {
+ addExcludeFromContext(apiKey, contextName, sessionUrl);
+ } else {
+ foundOneMatch = true;
+ }
+ }
+ }
+ if (!foundOneMatch) {
+ throw new Exception(
+ "Unexpected result: No url found in site tree matching regex " + regex);
+ }
+ }
+
+ /**
+ * Includes just one of the nodes that match the given regular expression in the context with
+ * the given name.
+ *
+ * Nodes that do not match the regular expression are excluded.
+ *
+ * @param contextName the name of the context.
+ * @param regex the regular expression to match the node/URL.
+ * @throws Exception if an error occurred while calling the API.
+ */
+ public void includeOneMatchingNodeInContext(String contextName, String regex) throws Exception {
+ List sessionUrls = getSessionUrls();
+ boolean foundOneMatch = false;
+ for (String sessionUrl : sessionUrls) {
+ if (sessionUrl.matches(regex)) {
+ if (foundOneMatch) {
+ context.excludeFromContext(contextName, regex);
+ } else {
+ foundOneMatch = true;
+ }
+ }
+ }
+ if (!foundOneMatch) {
+ throw new Exception(
+ "Unexpected result: No url found in site tree matching regex " + regex);
+ }
+ }
+
+ private List getSessionUrls() throws Exception {
+ List sessionUrls = new ArrayList<>();
+ ApiResponse response = core.urls();
+ if (response != null && response instanceof ApiResponseList) {
+ ApiResponseElement urlList =
+ (ApiResponseElement) ((ApiResponseList) response).getItems().get(0);
+ for (ApiResponse element : ((ApiResponseList) response).getItems()) {
+ URL url = createUrl(((ApiResponseElement) element).getValue());
+ sessionUrls.add(url.getProtocol() + "://" + url.getHost() + url.getPath());
+ }
+ System.out.println(urlList);
+ }
+ return sessionUrls;
+ }
+
+ /**
+ * Active scans the given site, that's in scope.
+ *
+ * The method returns only after the scan has finished.
+ *
+ * @param apiKey the API key, might be {@code null}.
+ * @param url the site to scan
+ * @throws Exception if an error occurred while calling the API.
+ * @deprecated (1.1.0) Use {@link #activeScanSiteInScope(String)} instead, the API key should be
+ * set using one of the {@code ClientApi} constructors.
+ */
+ @Deprecated
+ public void activeScanSiteInScope(String apiKey, String url) throws Exception {
+ ascan.scan(apiKey, url, "true", "true", "", "", "");
+ waitForAScanToFinish(url);
+ }
+
+ /**
+ * Active scans the given site, that's in scope.
+ *
+ *
The method returns only after the scan has finished.
+ *
+ * @param url the site to scan
+ * @throws Exception if an error occurred while calling the API.
+ * @since 1.1.0
+ */
+ public void activeScanSiteInScope(String url) throws Exception {
+ ascan.scan(url, "true", "true", "", "", "");
+ waitForAScanToFinish(url);
+ }
+
+ private void waitForAScanToFinish(String targetUrl) throws ClientApiException {
+ // Poll until spider finished
+ int status = 0;
+ while (status < 100) {
+ status = statusToInt(ascan.status(""));
+ if (debug) {
+ String format = "Scanning %s Progress: %d%%";
+ System.out.println(String.format(format, targetUrl, status));
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // Ignore
+ }
+ }
+ }
+
+ /**
+ * Convenience method to wait for ZAP to be ready to receive API calls, when started
+ * programmatically.
+ *
+ *
It attempts to establish a connection to ZAP's proxy, in the given time, throwing an
+ * exception if the connection is not successful. The connection attempts might be polled in one
+ * second interval.
+ *
+ * @param timeoutInSeconds the (maximum) number of seconds to wait for ZAP to start
+ * @throws ClientApiException if the timeout was reached or if the thread was interrupted while
+ * waiting
+ * @see #waitForSuccessfulConnectionToZap(int, int)
+ */
+ public void waitForSuccessfulConnectionToZap(int timeoutInSeconds) throws ClientApiException {
+ waitForSuccessfulConnectionToZap(timeoutInSeconds, DEFAULT_CONNECTION_POOLING_IN_MS);
+ }
+
+ /**
+ * Convenience method to wait for ZAP to be ready to receive API calls, when started
+ * programmatically.
+ *
+ *
It attempts to establish a connection to ZAP's proxy, in the given time, throwing an
+ * exception if the connection is not successful. The connection attempts are done with the
+ * given polling interval.
+ *
+ * @param timeoutInSeconds the (maximum) number of seconds to wait for ZAP to start
+ * @param pollingIntervalInMs the interval, in milliseconds, for connection polling
+ * @throws ClientApiException if the timeout was reached or if the thread was interrupted while
+ * waiting.
+ * @throws IllegalArgumentException if the interval for connection polling is negative.
+ * @see #waitForSuccessfulConnectionToZap(int)
+ */
+ public void waitForSuccessfulConnectionToZap(int timeoutInSeconds, int pollingIntervalInMs)
+ throws ClientApiException {
+ int timeoutInMs = (int) TimeUnit.SECONDS.toMillis(timeoutInSeconds);
+ int connectionTimeoutInMs = timeoutInMs;
+ boolean connectionSuccessful = false;
+ long startTime = System.currentTimeMillis();
+ do {
+ try (Socket socket = new Socket()) {
+ try {
+ socket.connect(
+ new InetSocketAddress(zapAddress, zapPort), connectionTimeoutInMs);
+ connectionSuccessful = true;
+ } catch (SocketTimeoutException ignore) {
+ throw newTimeoutConnectionToZap(timeoutInSeconds);
+ } catch (IOException ignore) {
+ // and keep trying but wait some time first...
+ try {
+ Thread.sleep(pollingIntervalInMs);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ClientApiException(
+ "The ClientApi was interrupted while sleeping between connection polling.",
+ e);
+ }
+
+ long ellapsedTime = System.currentTimeMillis() - startTime;
+ if (ellapsedTime >= timeoutInMs) {
+ throw newTimeoutConnectionToZap(timeoutInSeconds);
+ }
+ connectionTimeoutInMs = (int) (timeoutInMs - ellapsedTime);
+ }
+ } catch (IOException ignore) {
+ // the closing state doesn't matter.
+ }
+ } while (!connectionSuccessful);
+ }
+
+ private static ClientApiException newTimeoutConnectionToZap(int timeoutInSeconds) {
+ return new ClientApiException(
+ "Unable to connect to ZAP's proxy after " + timeoutInSeconds + " seconds.");
+ }
+
+ /**
+ * A simple HTTP request.
+ *
+ *
Contains the request URI and headers.
+ */
+ private static class HttpRequest {
+
+ private static final String GET_METHOD = "GET";
+
+ private final String method;
+ private final URL requestUri;
+ private final Map headers;
+ private final String body;
+
+ public HttpRequest(String method, URL url, String body) {
+ this.method = method;
+ this.requestUri = url;
+ this.headers = new HashMap<>();
+ this.body = body;
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ /**
+ * Gets the request URI of the request.
+ *
+ * @return the request URI.
+ */
+ public URL getRequestUri() {
+ return requestUri;
+ }
+
+ /**
+ * Adds a header with the given name and value.
+ *
+ * If a header with the given name already exists it is replaced with the new value.
+ *
+ * @param name the name of the header.
+ * @param value the value of the header.
+ */
+ public void addHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ /**
+ * Gets the headers of the HTTP request. An unmodifiable {@code Map} containing the headers
+ * (the keys correspond to the header names and the values for its contents).
+ *
+ * @return an unmodifiable {@code Map} containing the headers.
+ */
+ public Map getHeaders() {
+ return Collections.unmodifiableMap(headers);
+ }
+
+ public String getBody() {
+ return body;
+ }
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiException.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiException.java
index acf0ce8..ab49c27 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiException.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiException.java
@@ -3,13 +3,13 @@
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
- * Copyright 2012 The Zed Attack Proxy Team
+ * Copyright 2012 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -19,44 +19,42 @@
*/
package org.zaproxy.clientapi.core;
-
public class ClientApiException extends Exception {
- private static final long serialVersionUID = 1L;
-
- private final String code;
- private final String detail;
-
- public ClientApiException(Exception e) {
- super(e);
- this.code = null;
- this.detail = null;
- }
-
- public ClientApiException(String s) {
- super(s);
- this.code = null;
- this.detail = null;
- }
-
- public ClientApiException(String message, Exception cause) {
- super(message, cause);
- this.code = null;
- this.detail = null;
- }
-
- public ClientApiException(String message, String code, String detail) {
- super(message);
- this.code = code;
- this.detail = detail;
- }
-
- public String getCode() {
- return code;
- }
-
- public String getDetail() {
- return detail;
- }
-
+ private static final long serialVersionUID = 1L;
+
+ private final String code;
+ private final String detail;
+
+ public ClientApiException(Exception e) {
+ super(e);
+ this.code = null;
+ this.detail = null;
+ }
+
+ public ClientApiException(String s) {
+ super(s);
+ this.code = null;
+ this.detail = null;
+ }
+
+ public ClientApiException(String message, Exception cause) {
+ super(message, cause);
+ this.code = null;
+ this.detail = null;
+ }
+
+ public ClientApiException(String message, String code, String detail) {
+ super(message);
+ this.code = code;
+ this.detail = detail;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public String getDetail() {
+ return detail;
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiMain.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiMain.java
index 37c2894..7de0717 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiMain.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/core/ClientApiMain.java
@@ -1,330 +1,361 @@
-/*
- * Zed Attack Proxy (ZAP) and its related class files.
- *
- * ZAP is an HTTP/HTTPS proxy for assessing web application security.
- *
- * Copyright 2012 The Zed Attack Proxy Team
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.zaproxy.clientapi.core;
-
-import java.io.File;
-import java.net.ConnectException;
-import java.util.HashMap;
-import java.util.List;
-
-public class ClientApiMain {
-
- private HashMap params = new HashMap<>();
- private String zapaddr = "localhost";
- private int zapport = 8090;
- private Task task;
- private ClientApi api;
- private boolean debug = false;
-
- private enum Task{
- stop, showAlerts, checkAlerts, saveSession, newSession, activeScanUrl, activeScanSiteInScope,
- addExcludeRegexToContext, addIncludeRegexToContext, addIncludeOneMatchingNodeToContext
- }
-
- public static void main(String[] args){
- new ClientApiMain(args);
- }
-
- public ClientApiMain(String[] args){
- initialize(args);
- try {
- executeTask();
- }catch (Exception e){
- e.printStackTrace();
- showHelp();
- }
- }
-
- private void executeTask() throws Exception {
- try {
- switch(task){
- case stop:
- api.core.shutdown((String)params.get("apikey"));
- break;
- case checkAlerts:
- if (params.get("alertsFile") == null){
- System.out.println("No Alerts File Path Supplied\n");
- showHelp();
- System.exit(1);
- }
- File alertsFile = (File)params.get("alertsFile");
- if (!alertsFile.exists()){
- System.out.println("File not Found: "+alertsFile.getAbsolutePath());
- showHelp();
- System.exit(1);
- }
- if (params.get("outputFile") == null){
- api.checkAlerts(
- AlertsFile.getAlertsFromFile(alertsFile, "ignoreAlert"),
- AlertsFile.getAlertsFromFile(alertsFile, "requireAlert"));
- }else{
- File outFile = (File)params.get("outputFile");
- try {
- api.checkAlerts(
- AlertsFile.getAlertsFromFile(alertsFile, "ignoreAlert"),
- AlertsFile.getAlertsFromFile(alertsFile, "requireAlert"),
- outFile);
- } catch (AssertionError e){
- System.out.println(e.getMessage());
- System.exit(1);
- }
- }
- break;
- case showAlerts:
- List alerts = api.getAlerts(null, -1, -1);
- for (Alert alert : alerts) {
- System.out.println(alert.toString());
- }
- break;
- case saveSession:
- if (params.get("sessionName") == null){
- System.out.println("No session name supplied\n");
- showHelp();
- System.exit(1);
- }
- api.core.saveSession((String)params.get("apikey"), (String)params.get("sessionName"), "true");
- break;
- case newSession:
- if (params.get("sessionName") == null){
- api.core.newSession((String)params.get("apikey"), "", "true");
- }else{
- api.core.newSession((String)params.get("apikey"), (String)params.get("sessionName"), "true");
- }
- break;
- case activeScanUrl:
- if (params.get("url") == null){
- System.out.println("No url supplied\n");
- showHelp();
- System.exit(1);
- }else{
- api.ascan.scan((String)params.get("apikey"), (String)params.get("url"), "true", "false", "", "", "");
- }
- break;
- case activeScanSiteInScope:
- checkForUrlParam();
- api.activeScanSiteInScope((String)params.get("apikey"), (String)params.get("url"));
- break;
- case addExcludeRegexToContext:
- checkForContextNameParam();
- checkForRegexParam();
- api.addExcludeFromContext((String)params.get("apikey"), (String)params.get("contextName"), (String)params.get("regex"));
- break;
- case addIncludeRegexToContext:
- checkForContextNameParam();
- checkForRegexParam();
- api.addIncludeInContext((String)params.get("apikey"), (String)params.get("contextName"), (String)params.get("regex"));
- break;
- case addIncludeOneMatchingNodeToContext:
- checkForContextNameParam();
- checkForRegexParam();
- api.includeOneMatchingNodeInContext((String)params.get("apikey"), (String)params.get("contextName"), (String)params.get("regex"));
- break;
- }
- } catch (ConnectException e){
- System.out.println(e.getMessage()+String.format(": zapaddr=%s, zapport=%d\n", zapaddr, zapport));
- showHelp();
- System.exit(1);
- }
- }
-
- private void checkForRegexParam() {
- if(params.get("regex") == null){
- System.out.println("No regex supplied\n");
- showHelp();
- System.exit(1);
- }
- }
-
- private void checkForContextNameParam() {
- if (params.get("contextName") == null){
- System.out.println("No context name supplied\n");
- showHelp();
- System.exit(1);
- }
- }
-
- private void checkForUrlParam() {
- if (params.get("url") == null){
- System.out.println("No url supplied\n");
- showHelp();
- System.exit(1);
- }
- }
-
- private void initialize(String[] args) {
- if (args.length > 0){
- if (args[0].equalsIgnoreCase("help")){
- try {
- setTask(args[1]);
- }catch (IndexOutOfBoundsException e){
- showHelp();
- System.exit(1);
- }
- showHelp();
- System.exit(0);
- }
- setTask(args[0]);
- for (String arg: args){
- String[] pair = arg.split("=");
- if (pair.length == 2){
- if (pair[0].equalsIgnoreCase("zapaddr")){
- zapaddr = pair[1];
- } else if(pair[0].equalsIgnoreCase("zapport")){
- try {
- zapport = Integer.parseInt(pair[1]);
- } catch (NumberFormatException e){
- System.out.println("Invalid value to zapport, must be in integer: "+pair[1]);
- showHelp();
- System.exit(1);
- }
- }else if(pair[0].equalsIgnoreCase("debug") && pair[1].equalsIgnoreCase("true")){
- debug = true;
- }else if(pair[0].contains("File")){
- params.put(pair[0], new File(pair[1]));
- }
- else{
- params.put(pair[0], pair[1]);
- }
- }
- }
- } else {
- showHelp();
- System.exit(1);
- }
- api = new ClientApi(zapaddr, zapport, debug);
- }
-
- private void setTask(String arg) {
- try {
- task = Task.valueOf(arg);
- } catch (IllegalArgumentException e){
- System.out.println("Unknown Task: "+arg);
- showHelp();
- System.exit(1);
- }
- }
-
- private void showHelp() {
- String help = "";
- if (task == null){
- help = "usage: java -jar zap-api.jar [args]\n\n"+
- "Type 'java -jar zap-api.jar help ' for help on a specific subcommand.\n\n" +
- "Available subcommands:\n"+
- "\tstop\n"+
- "\tcheckAlerts\n"+
- "\tshowAlerts\n"+
- "\tsaveSession\n"+
- "\tnewSession\n";
- } else{
- // TODO add case for activeScanSiteInScope
- switch (task){
- case stop:
- help = "usage: stop [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar stop' \n\t\t" +
- "Stop zap listening on default settings (localhost:8090)\n\t" +
- "2. Type 'java -jar zap-api.jar stop zapaddr=192.168.1.1 apikey=1234' \n\t\t" +
- "Stop zap listening on 192.168.1.1:8090\n\t" +
- "3. Type 'java -jar zap-api.jar stop zapport=7080 apikey=1234' \n\t\t" +
- "Stop zap listening on localhost:7080\n\t" +
- "4. Type 'java -jar zap-api.jar stop zapaddr=192.168.1.1 zapport=7080 apikey=1234' \n\t\t" +
- "Stop zap listening on 192.168.1.1:7080\n\n";
- break;
- case checkAlerts:
- help = "usage: checkAlerts alertsFile={PATH} [outputFile={PATH}] [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples\n\t" +
- "1. Type 'java -jar zap-api.jar checkAlerts alertsFile=\"C:\\Users\\me\\My Documents\\alerts.xml\"' \n\t\t" +
- "Check alerts ignoring alerts from alertsFile, looking for required alerts from alertsFile, using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar checkAlerts alertsFile=\"C:\\Users\\me\\My Documents\\alerts.xml\" outputFile=\"C:\\Users\\me\\My Documents\\report.xml\"' \n\t\t" +
- "Check alerts ignoring alerts from alertsFile, looking for required alerts from alertsFile. Outputting results to report.xml, using zap listening on localhost:8090\n\t" +
- "3. Type 'java -jar zap-api.jar checkAlerts alertsFile=\"C:\\Users\\me\\My Documents\\alerts.xml\" outputFile=\"C:\\Users\\me\\My Documents\\report.xml\"' zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Check alerts ignoring alerts from alertsFile, looking for required alerts from alertsFile. Outputting results to report.xml, using zap listening on 192.168.1.1:7080\n" +
- "Note: for paths containing spaces ensure path is enclosed in quotes\n\n";
- break;
- case showAlerts:
- help = "usage: showAlerts [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar showAlerts' \n\t\t" +
- "Show alerts, using zap listening on default settings (localhost:8090)\n\t" +
- "2. Type 'java -jar zap-api.jar showAlerts zapaddr=192.168.1.1' \n\t\t" +
- "Show alerts, using zap listening on 192.168.1.1:8090\n\t" +
- "3. Type 'java -jar zap-api.jar showAlerts zapport=7080' \n\t\t" +
- "Show alerts, using zap listening on localhost:7080\n\t" +
- "4. Type 'java -jar zap-api.jar showAlerts zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Show alerts, using zap listening on 192.168.1.1:7080\n\n";
- break;
- case saveSession:
- help = "usage: saveSession sessionName={PATH} [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar saveSession sessionName=\"Users/me/My Documents/mysession/mysessionfile\"' \n\t\t" +
- "Save zap session using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar saveSession sessionName=\"Users/me/My Documents/mysession/mysessionfile\" zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Save zap session using zap listening on 192.168.1.1:7080\nNote: for paths containing spaces ensure path is enclosed in quotes\n\n";
- break;
- case newSession:
- help = "usage: newSession [sessionName={PATH}] [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar newSession' \n\t\t" +
- "Start new session using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar newSession zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Start new session using zap listening on 192.168.1.1:7080\n\t" +
- "3. Type 'java -jar zap-api.jar newSession sessionName=\"Users/me/My Documents/mysession/newsession\"' \n\t\t" +
- "Start new session using zap listening on localhost:8090, creating session files at /Users/me/My Documents/mysession/newsession\n\t" +
- "4. Type 'java -jar zap-api.jar newSession sessionName=\"Users/me/My Documents/mysession/mysessionfile\" zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Start new session using zap listening on 192.168.1.1:7080, creating session files at /Users/me/My Documents/mysession/newsession\n" +
- "Note: for paths containing spaces ensure path is enclosed in quotes";
- break;
- case activeScanUrl:
- help = "usage: activeScanUrl url={url} [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar activeScanUrl url=http://myurl.com/' \n\t\t" +
- "Execute and active scan on http://myurl.com/ using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar activeScanUrl url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Execute and active scan on http://myurl.com/ using zap listening on 192.168.1.1:7080\n\t";
- break;
- case addExcludeRegexToContext:
- help = "usage: addExcludeRegexToContext contextName={contextName} regex={regex} [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar addExcludeRegexToContext contextName=1 regex=\\Qhttp://example.com/area\\E.* \n\t\t" +
- "Urls that match the regex will be excluded from scope using context '1' using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar addExcludeRegexToContext url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Urls that match the regex will be excluded from scope using context '1' using zap listening on 192.168.1.1:7080\n\t";
- break;
- case addIncludeRegexToContext:
- help = "usage: addIncludeRegexToContext contextName={contextName} regex={regex} [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar addIncludeRegexToContext contextName=1 regex=\\Qhttp://example.com/area\\E.* \n\t\t" +
- "Urls that match the regex will be included in scope using context '1' using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar addIncludeRegexToContext url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "Urls that match the regex will be included in scope using context '1' using zap listening on 192.168.1.1:7080\n\t";
- break;
- case addIncludeOneMatchingNodeToContext:
- help = "usage: addIncludeOneMatchingNodeToContext contextName={contextName} regex={regex} [zapaddr={ip}] [zapport={port}]\n\n" +
- "Examples:\n\t" +
- "1. Type 'java -jar zap-api.jar addIncludeOneMatchingNodeToContext contextName=1 regex=\\Qhttp://example.com/area\\E.* \n\t\t" +
- "The first url from the current session that matches the regex will be included in scope using context '1'. Any other matching url will be excluded from scope using zap listening on localhost:8090\n\t" +
- "2. Type 'java -jar zap-api.jar addIncludeOneMatchingNodeToContext url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t" +
- "The first url from the current session that matches the regex will be included in scope using context '1'. Any other matching url will be excluded from scope using context '1' using zap listening on 192.168.1.1:7080\n\t";
- break;
- }
- }
- System.out.println(help);
- }
-}
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2012 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.core;
+
+import java.io.File;
+import java.net.ConnectException;
+import java.util.HashMap;
+import java.util.List;
+
+public class ClientApiMain {
+
+ private HashMap params = new HashMap<>();
+ private String zapaddr = "localhost";
+ private int zapport = 8090;
+ private Task task;
+ private ClientApi api;
+ private boolean debug = false;
+
+ private enum Task {
+ stop,
+ showAlerts,
+ checkAlerts,
+ saveSession,
+ newSession,
+ activeScanUrl,
+ activeScanSiteInScope,
+ addExcludeRegexToContext,
+ addIncludeRegexToContext,
+ addIncludeOneMatchingNodeToContext
+ }
+
+ public static void main(String[] args) {
+ new ClientApiMain(args);
+ }
+
+ public ClientApiMain(String[] args) {
+ initialize(args);
+ try {
+ executeTask();
+ } catch (Exception e) {
+ e.printStackTrace();
+ showHelp();
+ }
+ }
+
+ private void executeTask() throws Exception {
+ try {
+ switch (task) {
+ case stop:
+ api.core.shutdown();
+ break;
+ case checkAlerts:
+ if (params.get("alertsFile") == null) {
+ System.out.println("No Alerts File Path Supplied\n");
+ showHelp();
+ System.exit(1);
+ }
+ File alertsFile = (File) params.get("alertsFile");
+ if (!alertsFile.exists()) {
+ System.out.println("File not Found: " + alertsFile.getAbsolutePath());
+ showHelp();
+ System.exit(1);
+ }
+ if (params.get("outputFile") == null) {
+ api.checkAlerts(
+ AlertsFile.getAlertsFromFile(alertsFile, "ignoreAlert"),
+ AlertsFile.getAlertsFromFile(alertsFile, "requireAlert"));
+ } else {
+ File outFile = (File) params.get("outputFile");
+ try {
+ api.checkAlerts(
+ AlertsFile.getAlertsFromFile(alertsFile, "ignoreAlert"),
+ AlertsFile.getAlertsFromFile(alertsFile, "requireAlert"),
+ outFile);
+ } catch (AssertionError e) {
+ System.out.println(e.getMessage());
+ System.exit(1);
+ }
+ }
+ break;
+ case showAlerts:
+ List alerts = api.getAlerts(null, -1, -1);
+ for (Alert alert : alerts) {
+ System.out.println(alert.toString());
+ }
+ break;
+ case saveSession:
+ if (params.get("sessionName") == null) {
+ System.out.println("No session name supplied\n");
+ showHelp();
+ System.exit(1);
+ }
+ api.core.saveSession((String) params.get("sessionName"), "true");
+ break;
+ case newSession:
+ if (params.get("sessionName") == null) {
+ api.core.newSession("", "true");
+ } else {
+ api.core.newSession((String) params.get("sessionName"), "true");
+ }
+ break;
+ case activeScanUrl:
+ if (params.get("url") == null) {
+ System.out.println("No url supplied\n");
+ showHelp();
+ System.exit(1);
+ } else {
+ api.ascan.scan((String) params.get("url"), "true", "false", "", "", "");
+ }
+ break;
+ case activeScanSiteInScope:
+ checkForUrlParam();
+ api.activeScanSiteInScope((String) params.get("url"));
+ break;
+ case addExcludeRegexToContext:
+ checkForContextNameParam();
+ checkForRegexParam();
+ api.context.excludeFromContext(
+ (String) params.get("contextName"), (String) params.get("regex"));
+ break;
+ case addIncludeRegexToContext:
+ checkForContextNameParam();
+ checkForRegexParam();
+ api.context.includeInContext(
+ (String) params.get("contextName"), (String) params.get("regex"));
+ break;
+ case addIncludeOneMatchingNodeToContext:
+ checkForContextNameParam();
+ checkForRegexParam();
+ api.includeOneMatchingNodeInContext(
+ (String) params.get("contextName"), (String) params.get("regex"));
+ break;
+ }
+ } catch (ConnectException e) {
+ System.out.println(
+ e.getMessage() + String.format(": zapaddr=%s, zapport=%d\n", zapaddr, zapport));
+ showHelp();
+ System.exit(1);
+ }
+ }
+
+ private void checkForRegexParam() {
+ if (params.get("regex") == null) {
+ System.out.println("No regex supplied\n");
+ showHelp();
+ System.exit(1);
+ }
+ }
+
+ private void checkForContextNameParam() {
+ if (params.get("contextName") == null) {
+ System.out.println("No context name supplied\n");
+ showHelp();
+ System.exit(1);
+ }
+ }
+
+ private void checkForUrlParam() {
+ if (params.get("url") == null) {
+ System.out.println("No url supplied\n");
+ showHelp();
+ System.exit(1);
+ }
+ }
+
+ private void initialize(String[] args) {
+ if (args.length > 0) {
+ if (args[0].equalsIgnoreCase("help")) {
+ try {
+ setTask(args[1]);
+ } catch (IndexOutOfBoundsException e) {
+ showHelp();
+ System.exit(1);
+ }
+ showHelp();
+ System.exit(0);
+ }
+ setTask(args[0]);
+ for (String arg : args) {
+ String[] pair = arg.split("=", 2);
+ if (pair.length == 2) {
+ if (pair[0].equalsIgnoreCase("zapaddr")) {
+ zapaddr = pair[1];
+ } else if (pair[0].equalsIgnoreCase("zapport")) {
+ try {
+ zapport = Integer.parseInt(pair[1]);
+ } catch (NumberFormatException e) {
+ System.out.println(
+ "Invalid value to zapport, must be in integer: " + pair[1]);
+ showHelp();
+ System.exit(1);
+ }
+ } else if (pair[0].equalsIgnoreCase("debug")
+ && pair[1].equalsIgnoreCase("true")) {
+ debug = true;
+ } else if (pair[0].contains("File")) {
+ params.put(pair[0], new File(pair[1]));
+ } else {
+ params.put(pair[0], pair[1]);
+ }
+ }
+ }
+ } else {
+ showHelp();
+ System.exit(1);
+ }
+ api = new ClientApi(zapaddr, zapport, (String) params.get("apikey"), debug);
+ }
+
+ private void setTask(String arg) {
+ try {
+ task = Task.valueOf(arg);
+ } catch (IllegalArgumentException e) {
+ System.out.println("Unknown Task: " + arg);
+ showHelp();
+ System.exit(1);
+ }
+ }
+
+ private void showHelp() {
+ String help = "";
+ if (task == null) {
+ help =
+ "usage: java -jar zap-api.jar [args]\n\n"
+ + "Type 'java -jar zap-api.jar help ' for help on a specific subcommand.\n\n"
+ + "Available subcommands:\n"
+ + "\tstop\n"
+ + "\tcheckAlerts\n"
+ + "\tshowAlerts\n"
+ + "\tsaveSession\n"
+ + "\tnewSession\n";
+ } else {
+ switch (task) {
+ case stop:
+ help =
+ "usage: stop [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar stop' \n\t\t"
+ + "Stop zap listening on default settings (localhost:8090)\n\t"
+ + "2. Type 'java -jar zap-api.jar stop zapaddr=192.168.1.1 apikey=1234' \n\t\t"
+ + "Stop zap listening on 192.168.1.1:8090\n\t"
+ + "3. Type 'java -jar zap-api.jar stop zapport=7080 apikey=1234' \n\t\t"
+ + "Stop zap listening on localhost:7080\n\t"
+ + "4. Type 'java -jar zap-api.jar stop zapaddr=192.168.1.1 zapport=7080 apikey=1234' \n\t\t"
+ + "Stop zap listening on 192.168.1.1:7080\n\n";
+ break;
+ case checkAlerts:
+ help =
+ "usage: checkAlerts alertsFile={PATH} [outputFile={PATH}] [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples\n\t"
+ + "1. Type 'java -jar zap-api.jar checkAlerts alertsFile=\"C:\\Users\\me\\My Documents\\alerts.xml\"' \n\t\t"
+ + "Check alerts ignoring alerts from alertsFile, looking for required alerts from alertsFile, using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar checkAlerts alertsFile=\"C:\\Users\\me\\My Documents\\alerts.xml\" outputFile=\"C:\\Users\\me\\My Documents\\report.xml\"' \n\t\t"
+ + "Check alerts ignoring alerts from alertsFile, looking for required alerts from alertsFile. Outputting results to report.xml, using zap listening on localhost:8090\n\t"
+ + "3. Type 'java -jar zap-api.jar checkAlerts alertsFile=\"C:\\Users\\me\\My Documents\\alerts.xml\" outputFile=\"C:\\Users\\me\\My Documents\\report.xml\"' zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Check alerts ignoring alerts from alertsFile, looking for required alerts from alertsFile. Outputting results to report.xml, using zap listening on 192.168.1.1:7080\n"
+ + "Note: for paths containing spaces ensure path is enclosed in quotes\n\n";
+ break;
+ case showAlerts:
+ help =
+ "usage: showAlerts [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar showAlerts' \n\t\t"
+ + "Show alerts, using zap listening on default settings (localhost:8090)\n\t"
+ + "2. Type 'java -jar zap-api.jar showAlerts zapaddr=192.168.1.1' \n\t\t"
+ + "Show alerts, using zap listening on 192.168.1.1:8090\n\t"
+ + "3. Type 'java -jar zap-api.jar showAlerts zapport=7080' \n\t\t"
+ + "Show alerts, using zap listening on localhost:7080\n\t"
+ + "4. Type 'java -jar zap-api.jar showAlerts zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Show alerts, using zap listening on 192.168.1.1:7080\n\n";
+ break;
+ case saveSession:
+ help =
+ "usage: saveSession sessionName={PATH} [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar saveSession sessionName=\"Users/me/My Documents/mysession/mysessionfile\"' \n\t\t"
+ + "Save zap session using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar saveSession sessionName=\"Users/me/My Documents/mysession/mysessionfile\" zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Save zap session using zap listening on 192.168.1.1:7080\nNote: for paths containing spaces ensure path is enclosed in quotes\n\n";
+ break;
+ case newSession:
+ help =
+ "usage: newSession [sessionName={PATH}] [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar newSession' \n\t\t"
+ + "Start new session using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar newSession zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Start new session using zap listening on 192.168.1.1:7080\n\t"
+ + "3. Type 'java -jar zap-api.jar newSession sessionName=\"Users/me/My Documents/mysession/newsession\"' \n\t\t"
+ + "Start new session using zap listening on localhost:8090, creating session files at /Users/me/My Documents/mysession/newsession\n\t"
+ + "4. Type 'java -jar zap-api.jar newSession sessionName=\"Users/me/My Documents/mysession/mysessionfile\" zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Start new session using zap listening on 192.168.1.1:7080, creating session files at /Users/me/My Documents/mysession/newsession\n"
+ + "Note: for paths containing spaces ensure path is enclosed in quotes";
+ break;
+ case activeScanUrl:
+ help =
+ "usage: activeScanUrl url={url} [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar activeScanUrl url=http://myurl.com/' \n\t\t"
+ + "Execute an active scan on http://myurl.com/ using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar activeScanUrl url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Execute an active scan on http://myurl.com/ using zap listening on 192.168.1.1:7080\n\t";
+ break;
+ case activeScanSiteInScope:
+ help =
+ "usage: activeScanSiteInScope url={url} [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar activeScanSiteInScope url=http://example.com/' \n\t\t"
+ + "Execute an active scan for URLs in scope under http://example.com/ using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar activeScanSiteInScope url=http://example.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Execute an active scan for URLs in scope under http://example.com/ using zap listening on 192.168.1.1:7080\n\t";
+ break;
+ case addExcludeRegexToContext:
+ help =
+ "usage: addExcludeRegexToContext contextName={contextName} regex={regex} [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar addExcludeRegexToContext contextName=1 regex=\\Qhttp://example.com/area\\E.* \n\t\t"
+ + "Urls that match the regex will be excluded from scope using context '1' using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar addExcludeRegexToContext url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Urls that match the regex will be excluded from scope using context '1' using zap listening on 192.168.1.1:7080\n\t";
+ break;
+ case addIncludeRegexToContext:
+ help =
+ "usage: addIncludeRegexToContext contextName={contextName} regex={regex} [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar addIncludeRegexToContext contextName=1 regex=\\Qhttp://example.com/area\\E.* \n\t\t"
+ + "Urls that match the regex will be included in scope using context '1' using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar addIncludeRegexToContext url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "Urls that match the regex will be included in scope using context '1' using zap listening on 192.168.1.1:7080\n\t";
+ break;
+ case addIncludeOneMatchingNodeToContext:
+ help =
+ "usage: addIncludeOneMatchingNodeToContext contextName={contextName} regex={regex} [zapaddr={ip}] [zapport={port}]\n\n"
+ + "Examples:\n\t"
+ + "1. Type 'java -jar zap-api.jar addIncludeOneMatchingNodeToContext contextName=1 regex=\\Qhttp://example.com/area\\E.* \n\t\t"
+ + "The first url from the current session that matches the regex will be included in scope using context '1'. Any other matching url will be excluded from scope using zap listening on localhost:8090\n\t"
+ + "2. Type 'java -jar zap-api.jar addIncludeOneMatchingNodeToContext url=http://myurl.com/' zapaddr=192.168.1.1 zapport=7080' \n\t\t"
+ + "The first url from the current session that matches the regex will be included in scope using context '1'. Any other matching url will be excluded from scope using context '1' using zap listening on 192.168.1.1:7080\n\t";
+ break;
+ }
+ }
+ System.out.println(help);
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AccessControl.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AccessControl.java
new file mode 100644
index 0000000..5ddd26e
--- /dev/null
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AccessControl.java
@@ -0,0 +1,103 @@
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2020 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.gen;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.zaproxy.clientapi.core.ApiResponse;
+import org.zaproxy.clientapi.core.ClientApi;
+import org.zaproxy.clientapi.core.ClientApiException;
+
+/** This file was automatically generated. */
+@SuppressWarnings("javadoc")
+public class AccessControl {
+
+ private final ClientApi api;
+
+ public AccessControl(ClientApi api) {
+ this.api = api;
+ }
+
+ /**
+ * Gets the Access Control scan progress (percentage integer) for the given context ID.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse getScanProgress(String contextid) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ return api.callApi("accessControl", "view", "getScanProgress", map);
+ }
+
+ /**
+ * Gets the Access Control scan status (description string) for the given context ID.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse getScanStatus(String contextid) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ return api.callApi("accessControl", "view", "getScanStatus", map);
+ }
+
+ /**
+ * Starts an Access Control scan with the given context ID and user ID. (Optional parameters:
+ * user ID for Unauthenticated user, boolean identifying whether or not Alerts are raised, and
+ * the Risk level for the Alerts.) [This assumes the Access Control rules were previously
+ * established via ZAP gui and the necessary Context exported/imported.]
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse scan(
+ String contextid,
+ String userid,
+ String scanasunauthuser,
+ String raisealert,
+ String alertrisklevel)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ map.put("userId", userid);
+ if (scanasunauthuser != null) {
+ map.put("scanAsUnAuthUser", scanasunauthuser);
+ }
+ if (raisealert != null) {
+ map.put("raiseAlert", raisealert);
+ }
+ if (alertrisklevel != null) {
+ map.put("alertRiskLevel", alertrisklevel);
+ }
+ return api.callApi("accessControl", "action", "scan", map);
+ }
+
+ /**
+ * Generates an Access Control report for the given context ID and saves it based on the
+ * provided filename (path).
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse writeHTMLreport(String contextid, String filename)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ map.put("fileName", filename);
+ return api.callApi("accessControl", "action", "writeHTMLreport", map);
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Acsrf.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Acsrf.java
index 07412c7..68a9b14 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Acsrf.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Acsrf.java
@@ -1,14 +1,15 @@
-/* Zed Attack Proxy (ZAP) and its related class files.
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
- * Copyright 2016 the ZAP development team
+ * Copyright 2017 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,8 +17,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-
package org.zaproxy.clientapi.gen;
import java.util.HashMap;
@@ -26,63 +25,60 @@
import org.zaproxy.clientapi.core.ClientApi;
import org.zaproxy.clientapi.core.ClientApiException;
+/** This file was automatically generated. */
+@SuppressWarnings("javadoc")
+public class Acsrf extends org.zaproxy.clientapi.gen.deprecated.AcsrfDeprecated {
-/**
- * This file was automatically generated.
- */
-public class Acsrf {
+ private final ClientApi api;
+
+ public Acsrf(ClientApi api) {
+ super(api);
+ this.api = api;
+ }
- private ClientApi api = null;
+ /** Lists the names of all anti-CSRF tokens */
+ public ApiResponse optionTokensNames() throws ClientApiException {
+ return api.callApi("acsrf", "view", "optionTokensNames", null);
+ }
- public Acsrf(ClientApi api) {
- this.api = api;
- }
+ /** Define if ZAP should detect CSRF tokens by searching for partial matches */
+ public ApiResponse optionPartialMatchingEnabled() throws ClientApiException {
+ return api.callApi("acsrf", "view", "optionPartialMatchingEnabled", null);
+ }
- /**
- * Lists the names of all anti CSRF tokens
- */
- public ApiResponse optionTokensNames() throws ClientApiException {
- Map map = null;
- return api.callApi("acsrf", "view", "optionTokensNames", map);
- }
+ /** Adds an anti-CSRF token with the given name, enabled by default */
+ public ApiResponse addOptionToken(String string) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("String", string);
+ return api.callApi("acsrf", "action", "addOptionToken", map);
+ }
- /**
- * Adds an anti CSRF token with the given name, enabled by default
- */
- public ApiResponse addOptionToken(String apikey, String string) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("String", string);
- return api.callApi("acsrf", "action", "addOptionToken", map);
- }
+ /** Removes the anti-CSRF token with the given name */
+ public ApiResponse removeOptionToken(String string) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("String", string);
+ return api.callApi("acsrf", "action", "removeOptionToken", map);
+ }
- /**
- * Removes the anti CSRF token with the given name
- */
- public ApiResponse removeOptionToken(String apikey, String string) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("String", string);
- return api.callApi("acsrf", "action", "removeOptionToken", map);
- }
+ /** Define if ZAP should detect CSRF tokens by searching for partial matches. */
+ public ApiResponse setOptionPartialMatchingEnabled(boolean bool) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Boolean", Boolean.toString(bool));
+ return api.callApi("acsrf", "action", "setOptionPartialMatchingEnabled", map);
+ }
- /**
- * Generate a form for testing lack of anti CSRF tokens - typically invoked via ZAP
- */
- public byte[] genForm(String apikey, String hrefid) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("hrefId", hrefid);
- return api.callApiOther("acsrf", "other", "genForm", map);
- }
+ /** Generate a form for testing lack of anti-CSRF tokens - typically invoked via ZAP */
+ public byte[] genForm(String hrefid) throws ClientApiException {
+ return genFormActionUrl(hrefid, null);
+ }
+ /** Generate a form for testing lack of anti-CSRF tokens - typically invoked via ZAP */
+ public byte[] genFormActionUrl(String hrefid, String actionurl) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("hrefId", hrefid);
+ if (actionurl != null) {
+ map.put("actionUrl", actionurl);
+ }
+ return api.callApiOther("acsrf", "other", "genForm", map);
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AjaxSpider.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AjaxSpider.java
index 4455b80..3b09886 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AjaxSpider.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AjaxSpider.java
@@ -1,14 +1,15 @@
-/* Zed Attack Proxy (ZAP) and its related class files.
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
- * Copyright 2016 the ZAP development team
+ * Copyright 2016 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,8 +17,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-
package org.zaproxy.clientapi.gen;
import java.util.HashMap;
@@ -26,298 +25,479 @@
import org.zaproxy.clientapi.core.ClientApi;
import org.zaproxy.clientapi.core.ClientApiException;
-
-/**
- * This file was automatically generated.
- */
-public class AjaxSpider {
-
- private final ClientApi api;
-
- public AjaxSpider(ClientApi api) {
- this.api = api;
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse status() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "status", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse results(String start, String count) throws ClientApiException {
- Map map = new HashMap<>();
- if (start != null) {
- map.put("start", start);
- }
- if (count != null) {
- map.put("count", count);
- }
- return api.callApi("ajaxSpider", "view", "results", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse numberOfResults() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "numberOfResults", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionBrowserId() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionBrowserId", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionEventWait() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionEventWait", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionMaxCrawlDepth() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionMaxCrawlDepth", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionMaxCrawlStates() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionMaxCrawlStates", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionMaxDuration() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionMaxDuration", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionNumberOfBrowsers() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionNumberOfBrowsers", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionReloadWait() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionReloadWait", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionClickDefaultElems() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionClickDefaultElems", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionClickElemsOnce() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionClickElemsOnce", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse optionRandomInputs() throws ClientApiException {
- return api.callApi("ajaxSpider", "view", "optionRandomInputs", null);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed.
- */
- public ApiResponse scan(String apikey, String url, String inscope) throws ClientApiException {
- return scan(apikey, url, inscope, null, null);
- }
-
- /**
- * Runs the spider against the given URL and/or context, optionally, spidering everything in scope. The parameter 'contextName' can be used to constrain the scan to a Context, the option 'in scope' is ignored if a context was also specified. The parameter 'subtreeOnly' allows to restrict the spider under a site's subtree (using the specified 'url').
- *
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse scan(String apikey, String url, String inscope, String contextname, String subtreeonly) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- if (url != null) {
- map.put("url", url);
- }
- if (inscope != null) {
- map.put("inScope", inscope);
- }
- if (contextname != null) {
- map.put("contextName", contextname);
- }
- if (subtreeonly != null) {
- map.put("subtreeOnly", subtreeonly);
- }
- return api.callApi("ajaxSpider", "action", "scan", map);
- }
-
- /**
- * Runs the spider from the perspective of a User, obtained using the given context name and user name. The parameter 'url' allows to specify the starting point for the spider, otherwise it's used an existing URL from the context (if any). The parameter 'subtreeOnly' allows to restrict the spider under a site's subtree (using the specified 'url').
- *
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse scanAsUser(String apikey, String contextname, String username, String url, String subtreeonly) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("contextName", contextname);
- map.put("userName", username);
- if (url != null) {
- map.put("url", url);
- }
- if (subtreeonly != null) {
- map.put("subtreeOnly", subtreeonly);
- }
- return api.callApi("ajaxSpider", "action", "scanAsUser", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse stop(String apikey) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- return api.callApi("ajaxSpider", "action", "stop", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionBrowserId(String apikey, String string) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("String", string);
- return api.callApi("ajaxSpider", "action", "setOptionBrowserId", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionClickDefaultElems(String apikey, boolean bool) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Boolean", Boolean.toString(bool));
- return api.callApi("ajaxSpider", "action", "setOptionClickDefaultElems", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionClickElemsOnce(String apikey, boolean bool) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Boolean", Boolean.toString(bool));
- return api.callApi("ajaxSpider", "action", "setOptionClickElemsOnce", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionEventWait(String apikey, int i) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Integer", Integer.toString(i));
- return api.callApi("ajaxSpider", "action", "setOptionEventWait", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionMaxCrawlDepth(String apikey, int i) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Integer", Integer.toString(i));
- return api.callApi("ajaxSpider", "action", "setOptionMaxCrawlDepth", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionMaxCrawlStates(String apikey, int i) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Integer", Integer.toString(i));
- return api.callApi("ajaxSpider", "action", "setOptionMaxCrawlStates", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionMaxDuration(String apikey, int i) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Integer", Integer.toString(i));
- return api.callApi("ajaxSpider", "action", "setOptionMaxDuration", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionNumberOfBrowsers(String apikey, int i) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Integer", Integer.toString(i));
- return api.callApi("ajaxSpider", "action", "setOptionNumberOfBrowsers", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionRandomInputs(String apikey, boolean bool) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Boolean", Boolean.toString(bool));
- return api.callApi("ajaxSpider", "action", "setOptionRandomInputs", map);
- }
-
- /**
- * This component is optional and therefore the API will only work if it is installed
- */
- public ApiResponse setOptionReloadWait(String apikey, int i) throws ClientApiException {
- Map map = new HashMap<>();
- if (apikey != null) {
- map.put("apikey", apikey);
- }
- map.put("Integer", Integer.toString(i));
- return api.callApi("ajaxSpider", "action", "setOptionReloadWait", map);
- }
-
+/** This file was automatically generated. */
+@SuppressWarnings("javadoc")
+public class AjaxSpider extends org.zaproxy.clientapi.gen.deprecated.AjaxSpiderDeprecated {
+
+ private final ClientApi api;
+
+ public AjaxSpider(ClientApi api) {
+ super(api);
+ this.api = api;
+ }
+
+ /**
+ * Gets the allowed resources. The allowed resources are always fetched even if out of scope,
+ * allowing to include necessary resources (e.g. scripts) from 3rd-parties.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse allowedResources() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "allowedResources", null);
+ }
+
+ /**
+ * Gets the excluded elements. The excluded elements are not clicked during crawling, for
+ * example, to prevent logging out.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse excludedElements(String contextname) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextName", contextname);
+ return api.callApi("ajaxSpider", "view", "excludedElements", map);
+ }
+
+ /**
+ * Gets the current status of the crawler. Actual values are Stopped and Running.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse status() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "status", null);
+ }
+
+ /**
+ * Gets the current results of the crawler.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse results(String start, String count) throws ClientApiException {
+ Map map = new HashMap<>();
+ if (start != null) {
+ map.put("start", start);
+ }
+ if (count != null) {
+ map.put("count", count);
+ }
+ return api.callApi("ajaxSpider", "view", "results", map);
+ }
+
+ /**
+ * Gets the number of resources found.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse numberOfResults() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "numberOfResults", null);
+ }
+
+ /**
+ * Gets the full crawled content detected by the AJAX Spider. Returns a set of values based on
+ * 'inScope' URLs, 'outOfScope' URLs, and 'errors' encountered during the last/current run of
+ * the AJAX Spider.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse fullResults() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "fullResults", null);
+ }
+
+ /**
+ * Gets the configured browser to use for crawling.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionBrowserId() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionBrowserId", null);
+ }
+
+ /**
+ * Gets the time to wait after an event (in milliseconds). For example: the wait delay after the
+ * cursor hovers over an element, in order for a menu to display, etc.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionEventWait() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionEventWait", null);
+ }
+
+ /**
+ * Gets the configured value for the max crawl depth.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionMaxCrawlDepth() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionMaxCrawlDepth", null);
+ }
+
+ /**
+ * Gets the configured value for the maximum crawl states allowed.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionMaxCrawlStates() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionMaxCrawlStates", null);
+ }
+
+ /**
+ * Gets the configured max duration of the crawl, the value is in minutes.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionMaxDuration() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionMaxDuration", null);
+ }
+
+ /**
+ * Gets the configured number of browsers to be used.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionNumberOfBrowsers() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionNumberOfBrowsers", null);
+ }
+
+ /**
+ * Gets the configured time to wait after reloading the page, this value is in milliseconds.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionReloadWait() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionReloadWait", null);
+ }
+
+ /**
+ * Gets the configured value for 'Click Default Elements Only', HTML elements such as 'a',
+ * 'button', 'input', all associated with some action or links on the page.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionClickDefaultElems() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionClickDefaultElems", null);
+ }
+
+ /**
+ * Gets the value configured for the AJAX Spider to know if it should click on the elements only
+ * once.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionClickElemsOnce() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionClickElemsOnce", null);
+ }
+
+ /** This component is optional and therefore the API will only work if it is installed */
+ public ApiResponse optionEnableExtensions() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionEnableExtensions", null);
+ }
+
+ /**
+ * Gets if the AJAX Spider will use random values in form fields when crawling, if set to true.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse optionRandomInputs() throws ClientApiException {
+ return api.callApi("ajaxSpider", "view", "optionRandomInputs", null);
+ }
+
+ /**
+ * Runs the AJAX Spider against a given target.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse scan(String url, String inscope, String contextname, String subtreeonly)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (inscope != null) {
+ map.put("inScope", inscope);
+ }
+ if (contextname != null) {
+ map.put("contextName", contextname);
+ }
+ if (subtreeonly != null) {
+ map.put("subtreeOnly", subtreeonly);
+ }
+ return api.callApi("ajaxSpider", "action", "scan", map);
+ }
+
+ /**
+ * Runs the AJAX Spider from the perspective of a User of the web application.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse scanAsUser(
+ String contextname, String username, String url, String subtreeonly)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextName", contextname);
+ map.put("userName", username);
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (subtreeonly != null) {
+ map.put("subtreeOnly", subtreeonly);
+ }
+ return api.callApi("ajaxSpider", "action", "scanAsUser", map);
+ }
+
+ /**
+ * Stops the AJAX Spider.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse stop() throws ClientApiException {
+ return api.callApi("ajaxSpider", "action", "stop", null);
+ }
+
+ /**
+ * Adds an allowed resource.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse addAllowedResource(String regex, String enabled) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("regex", regex);
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ return api.callApi("ajaxSpider", "action", "addAllowedResource", map);
+ }
+
+ /**
+ * Adds an excluded element to a context.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse addExcludedElement(
+ String contextname,
+ String description,
+ String element,
+ String xpath,
+ String text,
+ String attributename,
+ String attributevalue,
+ String enabled)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextName", contextname);
+ map.put("description", description);
+ map.put("element", element);
+ if (xpath != null) {
+ map.put("xpath", xpath);
+ }
+ if (text != null) {
+ map.put("text", text);
+ }
+ if (attributename != null) {
+ map.put("attributeName", attributename);
+ }
+ if (attributevalue != null) {
+ map.put("attributeValue", attributevalue);
+ }
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ return api.callApi("ajaxSpider", "action", "addExcludedElement", map);
+ }
+
+ /**
+ * Modifies an excluded element of a context.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse modifyExcludedElement(
+ String contextname,
+ String description,
+ String element,
+ String descriptionnew,
+ String xpath,
+ String text,
+ String attributename,
+ String attributevalue,
+ String enabled)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextName", contextname);
+ map.put("description", description);
+ map.put("element", element);
+ if (descriptionnew != null) {
+ map.put("descriptionNew", descriptionnew);
+ }
+ if (xpath != null) {
+ map.put("xpath", xpath);
+ }
+ if (text != null) {
+ map.put("text", text);
+ }
+ if (attributename != null) {
+ map.put("attributeName", attributename);
+ }
+ if (attributevalue != null) {
+ map.put("attributeValue", attributevalue);
+ }
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ return api.callApi("ajaxSpider", "action", "modifyExcludedElement", map);
+ }
+
+ /**
+ * Removes an excluded element from a context.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse removeExcludedElement(String contextname, String description)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextName", contextname);
+ map.put("description", description);
+ return api.callApi("ajaxSpider", "action", "removeExcludedElement", map);
+ }
+
+ /**
+ * Removes an allowed resource.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse removeAllowedResource(String regex) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("regex", regex);
+ return api.callApi("ajaxSpider", "action", "removeAllowedResource", map);
+ }
+
+ /**
+ * Sets whether or not an allowed resource is enabled.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setEnabledAllowedResource(String regex, String enabled)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("regex", regex);
+ map.put("enabled", enabled);
+ return api.callApi("ajaxSpider", "action", "setEnabledAllowedResource", map);
+ }
+
+ /**
+ * Sets the configuration of the AJAX Spider to use one of the supported browsers.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionBrowserId(String string) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("String", string);
+ return api.callApi("ajaxSpider", "action", "setOptionBrowserId", map);
+ }
+
+ /**
+ * Sets whether or not the AJAX Spider will only click on the default HTML elements.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionClickDefaultElems(boolean bool) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Boolean", Boolean.toString(bool));
+ return api.callApi("ajaxSpider", "action", "setOptionClickDefaultElems", map);
+ }
+
+ /**
+ * When enabled, the crawler attempts to interact with each element (e.g., by clicking) only
+ * once.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionClickElemsOnce(boolean bool) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Boolean", Boolean.toString(bool));
+ return api.callApi("ajaxSpider", "action", "setOptionClickElemsOnce", map);
+ }
+
+ /** This component is optional and therefore the API will only work if it is installed */
+ public ApiResponse setOptionEnableExtensions(boolean bool) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Boolean", Boolean.toString(bool));
+ return api.callApi("ajaxSpider", "action", "setOptionEnableExtensions", map);
+ }
+
+ /**
+ * Sets the time to wait after an event (in milliseconds). For example: the wait delay after the
+ * cursor hovers over an element, in order for a menu to display, etc.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionEventWait(int i) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Integer", Integer.toString(i));
+ return api.callApi("ajaxSpider", "action", "setOptionEventWait", map);
+ }
+
+ /**
+ * Sets the maximum depth that the crawler can reach.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionMaxCrawlDepth(int i) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Integer", Integer.toString(i));
+ return api.callApi("ajaxSpider", "action", "setOptionMaxCrawlDepth", map);
+ }
+
+ /**
+ * Sets the maximum number of states that the crawler should crawl.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionMaxCrawlStates(int i) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Integer", Integer.toString(i));
+ return api.callApi("ajaxSpider", "action", "setOptionMaxCrawlStates", map);
+ }
+
+ /**
+ * The maximum time that the crawler is allowed to run.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionMaxDuration(int i) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Integer", Integer.toString(i));
+ return api.callApi("ajaxSpider", "action", "setOptionMaxDuration", map);
+ }
+
+ /**
+ * Sets the number of windows to be used by AJAX Spider.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionNumberOfBrowsers(int i) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Integer", Integer.toString(i));
+ return api.callApi("ajaxSpider", "action", "setOptionNumberOfBrowsers", map);
+ }
+
+ /**
+ * When enabled, inserts random values into form fields.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionRandomInputs(boolean bool) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Boolean", Boolean.toString(bool));
+ return api.callApi("ajaxSpider", "action", "setOptionRandomInputs", map);
+ }
+
+ /**
+ * Sets the time to wait after the page is loaded before interacting with it.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse setOptionReloadWait(int i) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("Integer", Integer.toString(i));
+ return api.callApi("ajaxSpider", "action", "setOptionReloadWait", map);
+ }
}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Alert.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Alert.java
new file mode 100644
index 0000000..5bd6940
--- /dev/null
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Alert.java
@@ -0,0 +1,298 @@
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2019 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.gen;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.zaproxy.clientapi.core.ApiResponse;
+import org.zaproxy.clientapi.core.ClientApi;
+import org.zaproxy.clientapi.core.ClientApiException;
+
+/** This file was automatically generated. */
+@SuppressWarnings("javadoc")
+public class Alert {
+
+ private final ClientApi api;
+
+ public Alert(ClientApi api) {
+ this.api = api;
+ }
+
+ /**
+ * Gets the alert with the given ID, the corresponding HTTP message can be obtained with the
+ * 'messageId' field and 'message' API method
+ */
+ public ApiResponse alert(String id) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("id", id);
+ return api.callApi("alert", "view", "alert", map);
+ }
+
+ /**
+ * Gets the alerts raised by ZAP, optionally filtering by URL or riskId, and paginating with
+ * 'start' position and 'count' of alerts
+ */
+ public ApiResponse alerts(String baseurl, String start, String count, String riskid)
+ throws ClientApiException {
+ return alerts(baseurl, start, count, riskid, null);
+ }
+
+ /**
+ * Gets the alerts raised by ZAP, optionally filtering by URL or riskId, and paginating with
+ * 'start' position and 'count' of alerts
+ */
+ public ApiResponse alerts(
+ String baseurl, String start, String count, String riskid, String contextname)
+ throws ClientApiException {
+ return alerts(baseurl, start, count, riskid, null, null);
+ }
+
+ /**
+ * Gets the alerts raised by ZAP, optionally filtering by URL or riskId, and paginating with
+ * 'start' position and 'count' of alerts
+ */
+ public ApiResponse alerts(
+ String baseurl,
+ String start,
+ String count,
+ String riskid,
+ String contextname,
+ String falsepositive)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ if (baseurl != null) {
+ map.put("baseurl", baseurl);
+ }
+ if (start != null) {
+ map.put("start", start);
+ }
+ if (count != null) {
+ map.put("count", count);
+ }
+ if (riskid != null) {
+ map.put("riskId", riskid);
+ }
+ if (contextname != null) {
+ map.put("contextName", contextname);
+ }
+ if (falsepositive != null) {
+ map.put("falsePositive", falsepositive);
+ }
+ return api.callApi("alert", "view", "alerts", map);
+ }
+
+ /** Gets number of alerts grouped by each risk level, optionally filtering by URL */
+ public ApiResponse alertsSummary(String baseurl) throws ClientApiException {
+ Map map = new HashMap<>();
+ if (baseurl != null) {
+ map.put("baseurl", baseurl);
+ }
+ return api.callApi("alert", "view", "alertsSummary", map);
+ }
+
+ /** Gets the number of alerts, optionally filtering by URL or riskId */
+ public ApiResponse numberOfAlerts(String baseurl, String riskid) throws ClientApiException {
+ Map map = new HashMap<>();
+ if (baseurl != null) {
+ map.put("baseurl", baseurl);
+ }
+ if (riskid != null) {
+ map.put("riskId", riskid);
+ }
+ return api.callApi("alert", "view", "numberOfAlerts", map);
+ }
+
+ /**
+ * Gets a summary of the alerts, optionally filtered by a 'url'. If 'recurse' is true then all
+ * alerts that apply to urls that start with the specified 'url' will be returned, otherwise
+ * only those on exactly the same 'url' (ignoring url parameters)
+ */
+ public ApiResponse alertsByRisk(String url, String recurse) throws ClientApiException {
+ Map map = new HashMap<>();
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (recurse != null) {
+ map.put("recurse", recurse);
+ }
+ return api.callApi("alert", "view", "alertsByRisk", map);
+ }
+
+ /** Gets a count of the alerts, optionally filtered as per alertsPerRisk */
+ public ApiResponse alertCountsByRisk(String url, String recurse) throws ClientApiException {
+ Map map = new HashMap<>();
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (recurse != null) {
+ map.put("recurse", recurse);
+ }
+ return api.callApi("alert", "view", "alertCountsByRisk", map);
+ }
+
+ /** Deletes all alerts of the current session. */
+ public ApiResponse deleteAllAlerts() throws ClientApiException {
+ return api.callApi("alert", "action", "deleteAllAlerts", null);
+ }
+
+ /**
+ * Deletes all the alerts optionally filtered by URL which fall within the Context with the
+ * provided name, risk, or base URL.
+ */
+ public ApiResponse deleteAlerts(String contextname, String baseurl, String riskid)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ if (contextname != null) {
+ map.put("contextName", contextname);
+ }
+ if (baseurl != null) {
+ map.put("baseurl", baseurl);
+ }
+ if (riskid != null) {
+ map.put("riskId", riskid);
+ }
+ return api.callApi("alert", "action", "deleteAlerts", map);
+ }
+
+ /** Deletes the alert with the given ID. */
+ public ApiResponse deleteAlert(String id) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("id", id);
+ return api.callApi("alert", "action", "deleteAlert", map);
+ }
+
+ /** Update the confidence of the alerts. */
+ public ApiResponse updateAlertsConfidence(String ids, String confidenceid)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("ids", ids);
+ map.put("confidenceId", confidenceid);
+ return api.callApi("alert", "action", "updateAlertsConfidence", map);
+ }
+
+ /** Update the risk of the alerts. */
+ public ApiResponse updateAlertsRisk(String ids, String riskid) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("ids", ids);
+ map.put("riskId", riskid);
+ return api.callApi("alert", "action", "updateAlertsRisk", map);
+ }
+
+ /** Update the alert with the given ID, with the provided details. */
+ public ApiResponse updateAlert(
+ String id,
+ String name,
+ String riskid,
+ String confidenceid,
+ String description,
+ String param,
+ String attack,
+ String otherinfo,
+ String solution,
+ String references,
+ String evidence,
+ String cweid,
+ String wascid)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("id", id);
+ map.put("name", name);
+ map.put("riskId", riskid);
+ map.put("confidenceId", confidenceid);
+ map.put("description", description);
+ if (param != null) {
+ map.put("param", param);
+ }
+ if (attack != null) {
+ map.put("attack", attack);
+ }
+ if (otherinfo != null) {
+ map.put("otherInfo", otherinfo);
+ }
+ if (solution != null) {
+ map.put("solution", solution);
+ }
+ if (references != null) {
+ map.put("references", references);
+ }
+ if (evidence != null) {
+ map.put("evidence", evidence);
+ }
+ if (cweid != null) {
+ map.put("cweId", cweid);
+ }
+ if (wascid != null) {
+ map.put("wascId", wascid);
+ }
+ return api.callApi("alert", "action", "updateAlert", map);
+ }
+
+ /**
+ * Add an alert associated with the given message ID, with the provided details. (The ID of the
+ * created alert is returned.)
+ */
+ public ApiResponse addAlert(
+ String messageid,
+ String name,
+ String riskid,
+ String confidenceid,
+ String description,
+ String param,
+ String attack,
+ String otherinfo,
+ String solution,
+ String references,
+ String evidence,
+ String cweid,
+ String wascid)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("messageId", messageid);
+ map.put("name", name);
+ map.put("riskId", riskid);
+ map.put("confidenceId", confidenceid);
+ map.put("description", description);
+ if (param != null) {
+ map.put("param", param);
+ }
+ if (attack != null) {
+ map.put("attack", attack);
+ }
+ if (otherinfo != null) {
+ map.put("otherInfo", otherinfo);
+ }
+ if (solution != null) {
+ map.put("solution", solution);
+ }
+ if (references != null) {
+ map.put("references", references);
+ }
+ if (evidence != null) {
+ map.put("evidence", evidence);
+ }
+ if (cweid != null) {
+ map.put("cweId", cweid);
+ }
+ if (wascid != null) {
+ map.put("wascId", wascid);
+ }
+ return api.callApi("alert", "action", "addAlert", map);
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AlertFilter.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AlertFilter.java
new file mode 100644
index 0000000..fd2e405
--- /dev/null
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/AlertFilter.java
@@ -0,0 +1,339 @@
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
+ *
+ * ZAP is an HTTP/HTTPS proxy for assessing web application security.
+ *
+ * Copyright 2016 The ZAP Development Team
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.zaproxy.clientapi.gen;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.zaproxy.clientapi.core.ApiResponse;
+import org.zaproxy.clientapi.core.ClientApi;
+import org.zaproxy.clientapi.core.ClientApiException;
+
+/** This file was automatically generated. */
+@SuppressWarnings("javadoc")
+public class AlertFilter extends org.zaproxy.clientapi.gen.deprecated.AlertFilterDeprecated {
+
+ private final ClientApi api;
+
+ public AlertFilter(ClientApi api) {
+ this.api = api;
+ }
+
+ /**
+ * Lists the alert filters of the context with the given ID.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse alertFilterList(String contextid) throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ return api.callApi("alertFilter", "view", "alertFilterList", map);
+ }
+
+ /**
+ * Lists the global alert filters.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse globalAlertFilterList() throws ClientApiException {
+ return api.callApi("alertFilter", "view", "globalAlertFilterList", null);
+ }
+
+ /**
+ * Adds a new alert filter for the context with the given ID.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ @Override
+ public ApiResponse addAlertFilter(
+ String contextid,
+ String ruleid,
+ String newlevel,
+ String url,
+ String urlisregex,
+ String parameter,
+ String enabled,
+ String parameterisregex,
+ String attack,
+ String attackisregex,
+ String evidence,
+ String evidenceisregex,
+ String methods)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ map.put("ruleId", ruleid);
+ map.put("newLevel", newlevel);
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (urlisregex != null) {
+ map.put("urlIsRegex", urlisregex);
+ }
+ if (parameter != null) {
+ map.put("parameter", parameter);
+ }
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ if (parameterisregex != null) {
+ map.put("parameterIsRegex", parameterisregex);
+ }
+ if (attack != null) {
+ map.put("attack", attack);
+ }
+ if (attackisregex != null) {
+ map.put("attackIsRegex", attackisregex);
+ }
+ if (evidence != null) {
+ map.put("evidence", evidence);
+ }
+ if (evidenceisregex != null) {
+ map.put("evidenceIsRegex", evidenceisregex);
+ }
+ if (methods != null) {
+ map.put("methods", methods);
+ }
+ return api.callApi("alertFilter", "action", "addAlertFilter", map);
+ }
+
+ /**
+ * Removes an alert filter from the context with the given ID.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ @Override
+ public ApiResponse removeAlertFilter(
+ String contextid,
+ String ruleid,
+ String newlevel,
+ String url,
+ String urlisregex,
+ String parameter,
+ String enabled,
+ String parameterisregex,
+ String attack,
+ String attackisregex,
+ String evidence,
+ String evidenceisregex,
+ String methods)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("contextId", contextid);
+ map.put("ruleId", ruleid);
+ map.put("newLevel", newlevel);
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (urlisregex != null) {
+ map.put("urlIsRegex", urlisregex);
+ }
+ if (parameter != null) {
+ map.put("parameter", parameter);
+ }
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ if (parameterisregex != null) {
+ map.put("parameterIsRegex", parameterisregex);
+ }
+ if (attack != null) {
+ map.put("attack", attack);
+ }
+ if (attackisregex != null) {
+ map.put("attackIsRegex", attackisregex);
+ }
+ if (evidence != null) {
+ map.put("evidence", evidence);
+ }
+ if (evidenceisregex != null) {
+ map.put("evidenceIsRegex", evidenceisregex);
+ }
+ if (methods != null) {
+ map.put("methods", methods);
+ }
+ return api.callApi("alertFilter", "action", "removeAlertFilter", map);
+ }
+
+ /**
+ * Adds a new global alert filter.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ @Override
+ public ApiResponse addGlobalAlertFilter(
+ String ruleid,
+ String newlevel,
+ String url,
+ String urlisregex,
+ String parameter,
+ String enabled,
+ String parameterisregex,
+ String attack,
+ String attackisregex,
+ String evidence,
+ String evidenceisregex,
+ String methods)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("ruleId", ruleid);
+ map.put("newLevel", newlevel);
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (urlisregex != null) {
+ map.put("urlIsRegex", urlisregex);
+ }
+ if (parameter != null) {
+ map.put("parameter", parameter);
+ }
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ if (parameterisregex != null) {
+ map.put("parameterIsRegex", parameterisregex);
+ }
+ if (attack != null) {
+ map.put("attack", attack);
+ }
+ if (attackisregex != null) {
+ map.put("attackIsRegex", attackisregex);
+ }
+ if (evidence != null) {
+ map.put("evidence", evidence);
+ }
+ if (evidenceisregex != null) {
+ map.put("evidenceIsRegex", evidenceisregex);
+ }
+ if (methods != null) {
+ map.put("methods", methods);
+ }
+ return api.callApi("alertFilter", "action", "addGlobalAlertFilter", map);
+ }
+
+ /**
+ * Removes a global alert filter.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ @Override
+ public ApiResponse removeGlobalAlertFilter(
+ String ruleid,
+ String newlevel,
+ String url,
+ String urlisregex,
+ String parameter,
+ String enabled,
+ String parameterisregex,
+ String attack,
+ String attackisregex,
+ String evidence,
+ String evidenceisregex,
+ String methods)
+ throws ClientApiException {
+ Map map = new HashMap<>();
+ map.put("ruleId", ruleid);
+ map.put("newLevel", newlevel);
+ if (url != null) {
+ map.put("url", url);
+ }
+ if (urlisregex != null) {
+ map.put("urlIsRegex", urlisregex);
+ }
+ if (parameter != null) {
+ map.put("parameter", parameter);
+ }
+ if (enabled != null) {
+ map.put("enabled", enabled);
+ }
+ if (parameterisregex != null) {
+ map.put("parameterIsRegex", parameterisregex);
+ }
+ if (attack != null) {
+ map.put("attack", attack);
+ }
+ if (attackisregex != null) {
+ map.put("attackIsRegex", attackisregex);
+ }
+ if (evidence != null) {
+ map.put("evidence", evidence);
+ }
+ if (evidenceisregex != null) {
+ map.put("evidenceIsRegex", evidenceisregex);
+ }
+ if (methods != null) {
+ map.put("methods", methods);
+ }
+ return api.callApi("alertFilter", "action", "removeGlobalAlertFilter", map);
+ }
+
+ /**
+ * Applies all currently enabled Global and Context alert filters.
+ *
+ * This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse applyAll() throws ClientApiException {
+ return api.callApi("alertFilter", "action", "applyAll", null);
+ }
+
+ /**
+ * Applies all currently enabled Context alert filters.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse applyContext() throws ClientApiException {
+ return api.callApi("alertFilter", "action", "applyContext", null);
+ }
+
+ /**
+ * Applies all currently enabled Global alert filters.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse applyGlobal() throws ClientApiException {
+ return api.callApi("alertFilter", "action", "applyGlobal", null);
+ }
+
+ /**
+ * Tests all currently enabled Global and Context alert filters.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse testAll() throws ClientApiException {
+ return api.callApi("alertFilter", "action", "testAll", null);
+ }
+
+ /**
+ * Tests all currently enabled Context alert filters.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse testContext() throws ClientApiException {
+ return api.callApi("alertFilter", "action", "testContext", null);
+ }
+
+ /**
+ * Tests all currently enabled Global alert filters.
+ *
+ *
This component is optional and therefore the API will only work if it is installed
+ */
+ public ApiResponse testGlobal() throws ClientApiException {
+ return api.callApi("alertFilter", "action", "testGlobal", null);
+ }
+}
diff --git a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Ascan.java b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Ascan.java
index 29ef0b5..ad4929b 100644
--- a/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Ascan.java
+++ b/subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/Ascan.java
@@ -1,14 +1,15 @@
-/* Zed Attack Proxy (ZAP) and its related class files.
+/*
+ * Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
- * Copyright 2016 the ZAP development team
+ * Copyright 2017 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,8 +17,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-
package org.zaproxy.clientapi.gen;
import java.util.HashMap;
@@ -26,659 +25,769 @@
import org.zaproxy.clientapi.core.ClientApi;
import org.zaproxy.clientapi.core.ClientApiException;
-
-/**
- * This file was automatically generated.
- */
-public class Ascan {
-
- private ClientApi api = null;
-
- public Ascan(ClientApi api) {
- this.api = api;
- }
-
- public ApiResponse status(String scanid) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- if (scanid != null) {
- map.put("scanId", scanid);
- }
- return api.callApi("ascan", "view", "status", map);
- }
-
- public ApiResponse scanProgress(String scanid) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- if (scanid != null) {
- map.put("scanId", scanid);
- }
- return api.callApi("ascan", "view", "scanProgress", map);
- }
-
- public ApiResponse messagesIds(String scanid) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- map.put("scanId", scanid);
- return api.callApi("ascan", "view", "messagesIds", map);
- }
-
- public ApiResponse alertsIds(String scanid) throws ClientApiException {
- Map map = null;
- map = new HashMap();
- map.put("scanId", scanid);
- return api.callApi("ascan", "view", "alertsIds", map);
- }
-
- public ApiResponse scans() throws ClientApiException {
- Map map = null;
- return api.callApi("ascan", "view", "scans", map);
- }
-
- public ApiResponse scanPolicyNames() throws ClientApiException {
- Map