use of org.zaproxy.zap.extension.dynssl.ExtensionDynSSL in project zaproxy by zaproxy.
the class CoreAPI method handleApiOther.
@Override
public HttpMessage handleApiOther(HttpMessage msg, String name, JSONObject params) throws ApiException {
if (OTHER_PROXY_PAC.equals(name)) {
final ProxyParam proxyParam = Model.getSingleton().getOptionsParam().getProxyParam();
final int port = proxyParam.getProxyPort();
try {
String domain = null;
if (proxyParam.isProxyIpAnyLocalAddress()) {
String localDomain = msg.getRequestHeader().getHostName();
if (!API.API_DOMAIN.equals(localDomain)) {
domain = localDomain;
}
}
if (domain == null) {
domain = proxyParam.getProxyIp();
}
String response = this.getPacFile(domain, port);
msg.setResponseHeader(API.getDefaultResponseHeader("text/html", response.length()));
msg.setResponseBody(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return msg;
} else if (OTHER_SET_PROXY.equals(name)) {
/* JSON string:
* {"type":1,
* "http": {"host":"proxy.corp.com","port":80},
* "ssl": {"host":"proxy.corp.com","port":80},
* "ftp":{"host":"proxy.corp.com","port":80},
* "socks":{"host":"proxy.corp.com","port":80},
* "shareSettings":true,"socksVersion":5,
* "proxyExcludes":"localhost, 127.0.0.1"}
*/
String proxyDetails = params.getString(PARAM_PROXY_DETAILS);
String response = "OK";
try {
try {
JSONObject json = JSONObject.fromObject(proxyDetails);
if (json.getInt("type") == 1) {
JSONObject httpJson = JSONObject.fromObject(json.get("http"));
String proxyHost = httpJson.getString("host");
int proxyPort = httpJson.getInt("port");
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Model.getSingleton().getOptionsParam().getConnectionParam().setProxyChainName(proxyHost);
Model.getSingleton().getOptionsParam().getConnectionParam().setProxyChainPort(proxyPort);
}
}
} catch (JSONException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PROXY_DETAILS);
}
msg.setResponseHeader(API.getDefaultResponseHeader("text/html", response.length()));
msg.setResponseBody(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return msg;
} else if (OTHER_ROOT_CERT.equals(name)) {
ExtensionDynSSL extDynSSL = (ExtensionDynSSL) Control.getSingleton().getExtensionLoader().getExtension(ExtensionDynSSL.EXTENSION_ID);
if (extDynSSL != null) {
try {
Certificate rootCA = extDynSSL.getRootCA();
if (rootCA == null) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
}
final StringWriter sw = new StringWriter();
try (final PemWriter pw = new PemWriter(sw)) {
pw.writeObject(new JcaMiscPEMGenerator(rootCA));
pw.flush();
}
String response = sw.toString();
msg.setResponseHeader(API.getDefaultResponseHeader("application/pkix-cert;", response.length()));
msg.setResponseBody(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR);
}
} else {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
}
return msg;
} else if (OTHER_XML_REPORT.equals(name)) {
try {
writeReportLastScanTo(msg, ScanReportType.XML);
return msg;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR);
}
} else if (OTHER_HTML_REPORT.equals(name)) {
try {
writeReportLastScanTo(msg, ScanReportType.HTML);
return msg;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR);
}
} else if (OTHER_MD_REPORT.equals(name)) {
try {
writeReportLastScanTo(msg, ScanReportType.MD);
return msg;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR);
}
} else if (OTHER_MESSAGE_HAR.equals(name)) {
byte[] responseBody;
try {
final HarEntries entries = new HarEntries();
TableHistory tableHistory = Model.getSingleton().getDb().getTableHistory();
RecordHistory recordHistory;
try {
recordHistory = tableHistory.read(this.getParam(params, PARAM_ID, -1));
} catch (HttpMalformedHeaderException | DatabaseException e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR);
}
if (recordHistory == null || recordHistory.getHistoryType() == HistoryReference.TYPE_TEMPORARY) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
}
entries.addEntry(HarUtils.createHarEntry(recordHistory.getHttpMessage()));
HarLog harLog = HarUtils.createZapHarLog();
harLog.setEntries(entries);
responseBody = HarUtils.harLogToByteArray(harLog);
} catch (Exception e) {
logger.error(e.getMessage(), e);
ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
}
try {
msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
} catch (HttpMalformedHeaderException e) {
logger.error("Failed to create response header: " + e.getMessage(), e);
}
msg.setResponseBody(responseBody);
return msg;
} else if (OTHER_MESSAGES_HAR.equals(name)) {
byte[] responseBody;
try {
final HarEntries entries = new HarEntries();
processHttpMessages(this.getParam(params, PARAM_BASE_URL, (String) null), this.getParam(params, PARAM_START, -1), this.getParam(params, PARAM_COUNT, -1), new Processor<RecordHistory>() {
@Override
public void process(RecordHistory recordHistory) {
entries.addEntry(HarUtils.createHarEntry(recordHistory.getHttpMessage()));
}
});
HarLog harLog = HarUtils.createZapHarLog();
harLog.setEntries(entries);
responseBody = HarUtils.harLogToByteArray(harLog);
} catch (Exception e) {
logger.error(e.getMessage(), e);
ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
}
try {
msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
} catch (HttpMalformedHeaderException e) {
logger.error("Failed to create response header: " + e.getMessage(), e);
}
msg.setResponseBody(responseBody);
return msg;
} else if (OTHER_SEND_HAR_REQUEST.equals(name)) {
byte[] responseBody = {};
HttpMessage request = null;
try {
request = HarUtils.createHttpMessage(params.getString(PARAM_REQUEST));
} catch (IOException e) {
ApiException apiException = new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REQUEST, e);
responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
}
if (request != null) {
if (!isValidForCurrentMode(request.getRequestHeader().getURI())) {
ApiException apiException = new ApiException(ApiException.Type.MODE_VIOLATION);
responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
} else {
boolean followRedirects = getParam(params, PARAM_FOLLOW_REDIRECTS, false);
try {
final HarEntries entries = new HarEntries();
sendRequest(request, followRedirects, new Processor<HttpMessage>() {
@Override
public void process(HttpMessage msg) {
entries.addEntry(HarUtils.createHarEntry(msg));
}
});
HarLog harLog = HarUtils.createZapHarLog();
harLog.setEntries(entries);
responseBody = HarUtils.harLogToByteArray(harLog);
} catch (ApiException e) {
responseBody = e.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
logger.error(e.getMessage(), e);
ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
}
}
}
try {
msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
} catch (HttpMalformedHeaderException e) {
logger.error("Failed to create response header: " + e.getMessage(), e);
}
msg.setResponseBody(responseBody);
return msg;
} else if (OTHER_SCRIPT_JS.equals(name)) {
try {
msg.setResponseBody(API_SCRIPT);
// Allow caching
msg.setResponseHeader(API.getDefaultResponseHeader("text/javascript", API_SCRIPT.length(), true));
msg.getResponseHeader().addHeader(HttpResponseHeader.CACHE_CONTROL, API_SCRIPT_CACHE_CONTROL);
} catch (HttpMalformedHeaderException e) {
logger.error("Failed to create response header: " + e.getMessage(), e);
}
return msg;
} else {
throw new ApiException(ApiException.Type.BAD_OTHER);
}
}
use of org.zaproxy.zap.extension.dynssl.ExtensionDynSSL 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, Model.getSingleton().getOptionsParam().getConnectionParam()));
} 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() {
@Override
public void run() {
try {
// Give the API a chance to return
sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
Control.getSingleton().shutdown(Model.getSingleton().getOptionsParam().getDatabaseParam().isCompactDatabase());
logger.info(Constant.PROGRAM_TITLE + " terminated.");
System.exit(0);
}
};
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);
boolean sameSession = false;
if (!session.isNewState()) {
try {
sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
} catch (IOException e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
if (Files.exists(sessionPath) && (!overwrite || sameSession)) {
throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
}
this.savingSession = true;
try {
Control.getSingleton().saveSession(filename, this);
} catch (Exception 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);
}
String fileName = session.getFileName();
if (fileName.endsWith(".session")) {
fileName = fileName.substring(0, fileName.length() - 8);
}
fileName += "-" + dateFormat.format(new Date()) + ".session";
this.savingSession = true;
try {
Control.getSingleton().snapshotSession(fileName, this);
} catch (Exception 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) {
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) {
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) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
} else if (ACTION_CLEAR_EXCLUDED_FROM_PROXY.equals(name)) {
try {
session.setExcludeFromProxyRegexs(new ArrayList<String>());
} 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);
} 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)) {
ExtensionDynSSL extDyn = (ExtensionDynSSL) Control.getSingleton().getExtensionLoader().getExtension(ExtensionDynSSL.EXTENSION_ID);
if (extDyn != null) {
try {
extDyn.createNewRootCa();
} catch (Exception e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
} 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)) {
final ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.NAME);
if (extAlert != null) {
extAlert.deleteAllAlerts();
} else {
try {
Model.getSingleton().getDb().getTableAlert().deleteAllAlerts();
} catch (DatabaseException e) {
logger.error(e.getMessage(), e);
}
SiteNode rootNode = (SiteNode) Model.getSingleton().getSession().getSiteTree().getRoot();
rootNode.deleteAllAlerts();
removeHistoryReferenceAlerts(rootNode);
}
} 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 {
throw new ApiException(ApiException.Type.BAD_ACTION);
}
return ApiResponseElement.OK;
}
Aggregations