use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.
the class HttpMessage method equals.
/**
* Compare if 2 message is the same. 2 messages are the same if: Host, port, path and query
* param and VALUEs are the same. For POST request, the body must be the same.
*
* @param object
* @return
*/
@Override
public boolean equals(Object object) {
if (!(object instanceof HttpMessage)) {
return false;
}
HttpMessage msg = (HttpMessage) object;
boolean result = false;
// compare method
if (!this.getRequestHeader().getMethod().equalsIgnoreCase(msg.getRequestHeader().getMethod())) {
return false;
}
// compare host, port and URI
URI uri1 = this.getRequestHeader().getURI();
URI uri2 = msg.getRequestHeader().getURI();
if (uri1 == null) {
if (uri2 != null) {
return false;
}
return true;
} else if (uri2 == null) {
return false;
}
try {
if (uri1.getHost() == null || uri2.getHost() == null || !uri1.getHost().equalsIgnoreCase(uri2.getHost())) {
return false;
}
if (uri1.getPort() != uri2.getPort()) {
return false;
}
String pathQuery1 = uri1.getPathQuery();
String pathQuery2 = uri2.getPathQuery();
if (pathQuery1 == null && pathQuery2 == null) {
return true;
} else if (pathQuery1 != null && pathQuery2 != null) {
return pathQuery1.equalsIgnoreCase(pathQuery2);
} else if (pathQuery1 == null || pathQuery2 == null) {
return false;
}
if (this.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST)) {
return this.getRequestBody().equals(msg.getRequestBody());
}
result = true;
} catch (URIException e) {
try {
result = this.getRequestHeader().getURI().toString().equalsIgnoreCase(msg.getRequestHeader().getURI().toString());
} catch (Exception e1) {
// ZAP: log error
log.error(e.getMessage(), e);
}
}
return result;
}
use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.
the class CoreAPI method handleApiAction.
@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
Session session = Model.getSingleton().getSession();
if (ACTION_ACCESS_URL.equals(name)) {
URI uri;
try {
uri = new URI(params.getString(PARAM_URL), true);
} catch (URIException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
}
HttpMessage request;
try {
request = new HttpMessage(new HttpRequestHeader(HttpRequestHeader.GET, uri, HttpHeader.HTTP11));
} catch (HttpMalformedHeaderException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
}
return sendHttpMessage(request, getParam(params, PARAM_FOLLOW_REDIRECTS, false), name);
} else if (ACTION_SHUTDOWN.equals(name)) {
Thread thread = new Thread("ZAP-Shutdown") {
@Override
public void run() {
try {
// Give the API a chance to return
sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
try {
Control.getSingleton().shutdown(Model.getSingleton().getOptionsParam().getDatabaseParam().isCompactDatabase());
logger.info(Constant.PROGRAM_TITLE + " terminated.");
} catch (Throwable e) {
logger.error("An error occurred while shutting down:", e);
} finally {
System.exit(Control.getSingleton().getExitStatus());
}
}
};
thread.start();
} else if (ACTION_SAVE_SESSION.equalsIgnoreCase(name)) {
// Ignore case for backwards compatibility
Path sessionPath = SessionUtils.getSessionPath(params.getString(PARAM_SESSION));
String filename = sessionPath.toAbsolutePath().toString();
final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);
if (Files.exists(sessionPath)) {
boolean sameSession = false;
if (overwrite && !session.isNewState()) {
try {
sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
} catch (IOException e) {
logger.error("Failed to check if same session path:", e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
if (!overwrite || sameSession) {
throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
}
}
this.savingSession = true;
try {
Control.getSingleton().saveSession(filename, this);
} catch (Exception e) {
logger.error("Failed to save the session:", e);
this.savingSession = false;
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
// Wait for notification that its worked ok
try {
while (this.savingSession) {
Thread.sleep(200);
}
} catch (InterruptedException e) {
// Probably not an error
logger.debug(e.getMessage(), e);
}
logger.debug("Can now return after saving session");
} else if (ACTION_SNAPSHOT_SESSION.equalsIgnoreCase(name)) {
// Ignore case for backwards compatibility
if (session.isNewState()) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
}
List<String> actions = Control.getSingleton().getExtensionLoader().getActiveActions();
if (!actions.isEmpty()) {
throw new ApiException(ApiException.Type.BAD_STATE, "Active actions prevent the session snapshot: " + actions);
}
String fileName = ApiUtils.getOptionalStringParam(params, PARAM_SESSION);
if (fileName == null || fileName.isEmpty()) {
fileName = session.getFileName();
if (fileName.endsWith(".session")) {
fileName = fileName.substring(0, fileName.length() - 8);
}
fileName += "-" + dateFormat.format(new Date()) + ".session";
} else {
Path sessionPath = SessionUtils.getSessionPath(fileName);
fileName = sessionPath.toAbsolutePath().toString();
if (Files.exists(sessionPath)) {
final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);
boolean sameSession = false;
try {
sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
} catch (IOException e) {
logger.error("Failed to check if same session path:", e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
if (!overwrite || sameSession) {
throw new ApiException(ApiException.Type.ALREADY_EXISTS, fileName);
}
}
}
this.savingSession = true;
try {
Control.getSingleton().snapshotSession(fileName, this);
} catch (Exception e) {
logger.error("Failed to snapshot the session:", e);
this.savingSession = false;
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
// Wait for notification that its worked ok
try {
while (this.savingSession) {
Thread.sleep(200);
}
} catch (InterruptedException e) {
// Probably not an error
logger.debug(e.getMessage(), e);
}
logger.debug("Can now return after saving session");
} else if (ACTION_LOAD_SESSION.equalsIgnoreCase(name)) {
// Ignore case for backwards compatibility
Path sessionPath = SessionUtils.getSessionPath(params.getString(PARAM_SESSION));
String filename = sessionPath.toAbsolutePath().toString();
if (!Files.exists(sessionPath)) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST, filename);
}
try {
Control.getSingleton().runCommandLineOpenSession(filename);
} catch (Exception e) {
logger.error("Failed to load the session:", e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
} else if (ACTION_NEW_SESSION.equalsIgnoreCase(name)) {
// Ignore case for backwards compatibility
String sessionName = null;
try {
sessionName = params.getString(PARAM_SESSION);
} catch (Exception e1) {
// Ignore
}
if (sessionName == null || sessionName.length() == 0) {
// Create a new 'unnamed' session
Control.getSingleton().discardSession();
try {
Control.getSingleton().newSession();
} catch (Exception e) {
logger.error("Failed to create a new session:", e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
} else {
Path sessionPath = SessionUtils.getSessionPath(sessionName);
String filename = sessionPath.toAbsolutePath().toString();
final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);
if (Files.exists(sessionPath) && !overwrite) {
throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
}
try {
Control.getSingleton().runCommandLineNewSession(filename);
} catch (Exception e) {
logger.error("Failed to create a new session:", e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
} else if (ACTION_CLEAR_EXCLUDED_FROM_PROXY.equals(name)) {
try {
session.setExcludeFromProxyRegexs(new ArrayList<>());
} catch (DatabaseException e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
} else if (ACTION_EXCLUDE_FROM_PROXY.equals(name)) {
String regex = params.getString(PARAM_REGEX);
try {
session.addExcludeFromProxyRegex(regex);
} catch (DatabaseException e) {
logger.error(e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
} catch (PatternSyntaxException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REGEX);
}
} else if (ACTION_SET_HOME_DIRECTORY.equals(name)) {
File f = new File(params.getString(PARAM_DIR));
if (f.exists() && f.isDirectory()) {
Model.getSingleton().getOptionsParam().setUserDirectory(f);
} else {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_DIR);
}
} else if (ACTION_SET_MODE.equals(name)) {
try {
Mode mode = Mode.valueOf(params.getString(PARAM_MODE).toLowerCase());
if (View.isInitialised()) {
View.getSingleton().getMainFrame().getMainToolbarPanel().setMode(mode);
View.getSingleton().getMainFrame().getMainMenuBar().setMode(mode);
} else {
Control.getSingleton().setMode(mode);
}
} catch (Exception e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_MODE);
}
} else if (ACTION_GENERATE_ROOT_CA.equals(name)) {
return getNetworkImplementor().handleApiAction("generateRootCaCert", params);
} else if (ACTION_SEND_REQUEST.equals(name)) {
HttpMessage request;
try {
request = createRequest(params.getString(PARAM_REQUEST));
} catch (HttpMalformedHeaderException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REQUEST, e);
}
validateForCurrentMode(request);
return sendHttpMessage(request, getParam(params, PARAM_FOLLOW_REDIRECTS, false), name);
} else if (ACTION_DELETE_ALL_ALERTS.equals(name)) {
return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiAction(name, params);
} else if (ACTION_DELETE_ALERT.equals(name)) {
return API.getInstance().getImplementors().get(AlertAPI.PREFIX).handleApiAction(name, params);
} else if (ACTION_COLLECT_GARBAGE.equals(name)) {
System.gc();
return ApiResponseElement.OK;
} else if (ACTION_DELETE_SITE_NODE.equals(name)) {
try {
String url = params.getString(PARAM_URL);
String method = getParam(params, PARAM_METHOD, "GET");
String postData = getParam(params, PARAM_POST_DATA, "");
URI uri = new URI(url, true);
SiteMap siteMap = session.getSiteTree();
SiteNode siteNode = siteMap.findNode(uri, method, postData);
if (siteNode == null) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST, PARAM_URL);
}
if (getExtHistory() != null) {
getExtHistory().purge(siteMap, siteNode);
}
return ApiResponseElement.OK;
} catch (URIException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
}
} else if (ACTION_ADD_PROXY_CHAIN_EXCLUDED_DOMAIN.equals(name)) {
try {
ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
String value = params.getString(PARAM_VALUE);
DomainMatcher domain;
if (getParam(params, PARAM_IS_REGEX, false)) {
domain = new DomainMatcher(DomainMatcher.createPattern(value));
} else {
domain = new DomainMatcher(value);
}
domain.setEnabled(getParam(params, PARAM_IS_ENABLED, true));
List<DomainMatcher> domains = new ArrayList<>(connectionParam.getProxyExcludedDomains());
domains.add(domain);
connectionParam.setProxyExcludedDomains(domains);
} catch (IllegalArgumentException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_VALUE, e);
}
} else if (ACTION_MODIFY_PROXY_CHAIN_EXCLUDED_DOMAIN.equals(name)) {
try {
ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
int idx = params.getInt(PARAM_IDX);
if (idx < 0 || idx >= connectionParam.getProxyExcludedDomains().size()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
}
DomainMatcher oldDomain = connectionParam.getProxyExcludedDomains().get(idx);
String value = getParam(params, PARAM_VALUE, oldDomain.getValue());
if (value.isEmpty()) {
value = oldDomain.getValue();
}
DomainMatcher newDomain;
if (getParam(params, PARAM_IS_REGEX, oldDomain.isRegex())) {
newDomain = new DomainMatcher(DomainMatcher.createPattern(value));
} else {
newDomain = new DomainMatcher(value);
}
newDomain.setEnabled(getParam(params, PARAM_IS_ENABLED, oldDomain.isEnabled()));
if (!oldDomain.equals(newDomain)) {
List<DomainMatcher> domains = new ArrayList<>(connectionParam.getProxyExcludedDomains());
domains.set(idx, newDomain);
connectionParam.setProxyExcludedDomains(domains);
}
} catch (JSONException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
} catch (IllegalArgumentException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_VALUE, e);
}
} else if (ACTION_REMOVE_PROXY_CHAIN_EXCLUDED_DOMAIN.equals(name)) {
try {
ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
int idx = params.getInt(PARAM_IDX);
if (idx < 0 || idx >= connectionParam.getProxyExcludedDomains().size()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX);
}
List<DomainMatcher> domains = new ArrayList<>(connectionParam.getProxyExcludedDomains());
domains.remove(idx);
connectionParam.setProxyExcludedDomains(domains);
} catch (JSONException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_IDX, e);
}
} else if (ACTION_ENABLE_ALL_PROXY_CHAIN_EXCLUDED_DOMAINS.equals(name)) {
setProxyChainExcludedDomainsEnabled(true);
} else if (ACTION_DISABLE_ALL_PROXY_CHAIN_EXCLUDED_DOMAINS.equals(name)) {
setProxyChainExcludedDomainsEnabled(false);
} else if (ACTION_OPTION_MAXIMUM_ALERT_INSTANCES.equals(name)) {
try {
getAlertParam(ApiException.Type.BAD_ACTION).setMaximumInstances(params.getInt(PARAM_NUMBER_OF_INSTANCES));
} catch (JSONException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_NUMBER_OF_INSTANCES, e);
}
} else if (ACTION_OPTION_MERGE_RELATED_ALERTS.equals(name)) {
try {
getAlertParam(ApiException.Type.BAD_ACTION).setMergeRelatedIssues(params.getBoolean(PARAM_ENABLED));
} catch (JSONException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_ENABLED, e);
}
} else if (ACTION_OPTION_ALERT_OVERRIDES_FILE_PATH.equals(name)) {
String filePath = getParam(params, PARAM_FILE_PATH, "");
if (!filePath.isEmpty()) {
File file = new File(filePath);
if (!file.isFile() || !file.canRead()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE_PATH);
}
}
getAlertParam(ApiException.Type.BAD_ACTION).setOverridesFilename(filePath);
if (!Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class).reloadOverridesFile()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE_PATH);
}
} else if (ACTION_ENABLE_PKCS12_CLIENT_CERTIFICATE.equals(name)) {
String filePath = getParam(params, PARAM_FILE_PATH, "");
if (!filePath.isEmpty()) {
File file = new File(filePath);
if (!file.isFile() || !file.canRead()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE_PATH);
}
}
String password = getParam(params, PARAM_PASSWORD, "");
if (password.isEmpty()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PASSWORD);
}
int certIndex = getParam(params, PARAM_INDEX, 0);
if (certIndex < 0) {
certIndex = 0;
}
OptionsParamCertificate certParams = Model.getSingleton().getOptionsParam().getCertificateParam();
try {
SSLContextManager contextManager = certParams.getSSLContextManager();
int ksIndex = contextManager.loadPKCS12Certificate(filePath, password);
contextManager.unlockKey(ksIndex, certIndex, password);
contextManager.setDefaultKey(ksIndex, certIndex);
certParams.setActiveCertificate();
certParams.setEnableCertificate(true);
logger.info("Client Certificate enabled from API");
} catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
logger.error("The certificate could not be enabled due to an error", ex);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, ex);
}
return ApiResponseElement.OK;
} else if (ACTION_DISABLE_CLIENT_CERTIFICATE.equals(name)) {
Model.getSingleton().getOptionsParam().getCertificateParam().setEnableCertificate(false);
logger.info("Client Certificate disabled from API");
return ApiResponseElement.OK;
} else {
throw new ApiException(ApiException.Type.BAD_ACTION);
}
return ApiResponseElement.OK;
}
use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.
the class ActiveScanAPI method scanURL.
private int scanURL(String url, User user, boolean scanChildren, boolean scanJustInScope, String method, String postData, ScanPolicy policy, Context context) throws ApiException {
boolean useUrl = true;
if (url == null || url.isEmpty()) {
if (context == null || !context.hasNodesInContextFromSiteTree()) {
throw new ApiException(Type.MISSING_PARAMETER, PARAM_URL);
}
useUrl = false;
} else if (context != null && !context.isInContext(url)) {
throw new ApiException(Type.URL_NOT_IN_CONTEXT, PARAM_URL);
}
StructuralNode node = null;
if (useUrl) {
URI startURI;
try {
if (scanChildren && url.endsWith("/")) {
// Always choose the non leaf node if scanChildren option selected
url = url.substring(0, url.length() - 1);
}
startURI = new URI(url, true);
} catch (URIException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e);
}
String scheme = startURI.getScheme();
if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL + " does not have a scheme.");
}
try {
Model model = Model.getSingleton();
node = SessionStructure.find(model, startURI, method, postData);
if (node == null && "GET".equalsIgnoreCase(method)) {
// Check if there's a non-leaf node that matches the URI, to scan the subtree.
// (GET is the default method, but non-leaf nodes do not have any method.)
node = SessionStructure.find(model, startURI, null, postData);
}
} catch (Exception e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
}
if (node == null) {
throw new ApiException(ApiException.Type.URL_NOT_FOUND);
}
}
Target target;
if (useUrl) {
target = new Target(node);
target.setContext(context);
} else {
target = new Target(context);
}
target.setRecurse(scanChildren);
target.setInScopeOnly(scanJustInScope);
switch(Control.getSingleton().getMode()) {
case safe:
throw new ApiException(ApiException.Type.MODE_VIOLATION);
case protect:
if ((useUrl && !Model.getSingleton().getSession().isInScope(url)) || (context != null && !context.isInScope())) {
throw new ApiException(ApiException.Type.MODE_VIOLATION);
}
// No problem
break;
case standard:
// No problem
break;
case attack:
// No problem
break;
}
Object[] objs = new Object[] {};
if (policy != null) {
objs = new Object[] { policy };
}
return controller.startScan(null, target, user, objs);
}
use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.
the class SpiderController method addSeed.
/**
* Adds a new seed, if it wasn't already processed.
*
* @param uri the uri
* @param method the http method used for fetching the resource
*/
protected void addSeed(URI uri, String method) {
SpiderResourceFound resourceFound = SpiderResourceFound.builder().setUri(uri.toString()).setMethod(method).build();
// Check if the uri was processed already
String resourceIdentifier = "";
try {
resourceIdentifier = buildCanonicalResourceIdentifier(uri, resourceFound);
} catch (URIException e) {
return;
}
synchronized (visitedResources) {
if (visitedResources.contains(resourceIdentifier)) {
log.debug("URI already visited: " + uri);
return;
} else {
visitedResources.add(resourceIdentifier);
}
}
// Create and submit the new task
SpiderTask task = new SpiderTask(spider, resourceFound, uri);
spider.submitTask(task);
// Add the uri to the found list
spider.notifyListenersFoundURI(uri.toString(), method, FetchStatus.SEED);
}
use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.
the class SpiderTask method processResource.
/**
* Process a resource, searching for links (uris) to other resources.
*
* @param message the HTTP Message
*/
private void processResource(HttpMessage message) {
List<SpiderParser> parsers = parent.getController().getParsers();
// Prepare the Jericho source
Source source = new Source(message.getResponseBody().toString());
// Get the full path of the file
String path = null;
try {
path = message.getRequestHeader().getURI().getPath();
} catch (URIException e) {
} finally {
// Handle null paths.
if (path == null)
path = "";
}
// Parse the resource
boolean alreadyConsumed = false;
for (SpiderParser parser : parsers) {
if (parser.canParseResource(message, path, alreadyConsumed)) {
if (log.isDebugEnabled())
log.debug("Parser " + parser + " can parse resource '" + path + "'");
if (parser.parseResource(message, source, resourceFound.getDepth())) {
alreadyConsumed = true;
}
} else {
if (log.isDebugEnabled())
log.debug("Parser " + parser + " cannot parse resource '" + path + "'");
}
}
}
Aggregations