use of net.sf.json.JSONObject 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 net.sf.json.JSONObject in project zaproxy by zaproxy.
the class API method handleApiRequest.
public boolean handleApiRequest(HttpRequestHeader requestHeader, HttpInputStream httpIn, HttpOutputStream httpOut, boolean force) throws IOException {
String url = requestHeader.getURI().toString();
Format format = Format.OTHER;
ApiImplementor callbackImpl = null;
ApiImplementor shortcutImpl = null;
// Check for callbacks
if (url.contains(CALL_BACK_URL)) {
if (!isPermittedAddr(requestHeader)) {
return true;
}
logger.debug("handleApiRequest Callback: " + url);
for (Entry<String, ApiImplementor> callback : callBacks.entrySet()) {
if (url.startsWith(callback.getKey())) {
callbackImpl = callback.getValue();
break;
}
}
}
String path = requestHeader.getURI().getPath();
if (path != null) {
for (Entry<String, ApiImplementor> shortcut : shortcuts.entrySet()) {
if (path.startsWith(shortcut.getKey())) {
shortcutImpl = shortcut.getValue();
break;
}
}
}
if (shortcutImpl == null && callbackImpl == null && !url.startsWith(API_URL) && !url.startsWith(API_URL_S) && !force) {
return false;
}
if (!isPermittedAddr(requestHeader)) {
return true;
}
if (getOptionsParamApi().isSecureOnly() && !requestHeader.isSecure()) {
// Insecure request with secure only set, always ignore
logger.debug("handleApiRequest rejecting insecure request");
return true;
}
logger.debug("handleApiRequest " + url);
HttpMessage msg = new HttpMessage();
msg.setRequestHeader(requestHeader);
if (requestHeader.getContentLength() > 0) {
msg.setRequestBody(httpIn.readRequestBody(requestHeader));
}
String component = null;
ApiImplementor impl = null;
RequestType reqType = null;
String contentType = "text/plain; charset=UTF-8";
String response = "";
String name = null;
boolean error = false;
try {
JSONObject params = getParams(requestHeader.getURI().getEscapedQuery());
if (shortcutImpl != null) {
if (!getOptionsParamApi().isDisableKey() && !getOptionsParamApi().isNoKeyForSafeOps()) {
if (!this.hasValidKey(requestHeader, params)) {
throw new ApiException(ApiException.Type.BAD_API_KEY);
}
}
msg = shortcutImpl.handleShortcut(msg);
} else if (callbackImpl != null) {
// Callbacks have suitably random URLs and therefore don't require keys/nonces
response = callbackImpl.handleCallBack(msg);
} else {
// Parse the query:
// format of url is http://zap/format/component/reqtype/name/?params
// 0 1 2 3 4 5 6
String[] elements = url.split("/");
if (elements.length > 3 && elements[3].equalsIgnoreCase("favicon.ico")) {
// Treat the favicon as a special case:)
if (!getOptionsParamApi().isUiEnabled()) {
throw new ApiException(ApiException.Type.DISABLED);
}
InputStream is = API.class.getResourceAsStream("/resource/zap.ico");
byte[] icon = new byte[is.available()];
is.read(icon);
is.close();
msg.setResponseHeader(getDefaultResponseHeader(contentType));
msg.getResponseHeader().setContentLength(icon.length);
httpOut.write(msg.getResponseHeader());
httpOut.write(icon);
httpOut.flush();
httpOut.close();
httpIn.close();
return true;
} else if (elements.length > 3) {
try {
format = Format.valueOf(elements[3].toUpperCase());
switch(format) {
case JSON:
contentType = "application/json; charset=UTF-8";
break;
case JSONP:
contentType = "application/javascript; charset=UTF-8";
break;
case XML:
contentType = "text/xml; charset=UTF-8";
break;
case HTML:
contentType = "text/html; charset=UTF-8";
break;
case UI:
contentType = "text/html; charset=UTF-8";
break;
default:
break;
}
} catch (IllegalArgumentException e) {
format = Format.HTML;
throw new ApiException(ApiException.Type.BAD_FORMAT);
}
}
if (elements.length > 4) {
component = elements[4];
impl = implementors.get(component);
if (impl == null) {
throw new ApiException(ApiException.Type.NO_IMPLEMENTOR);
}
}
if (elements.length > 5) {
try {
reqType = RequestType.valueOf(elements[5]);
} catch (IllegalArgumentException e) {
throw new ApiException(ApiException.Type.BAD_TYPE);
}
}
if (elements.length > 6) {
name = elements[6];
if (name != null && name.indexOf("?") > 0) {
name = name.substring(0, name.indexOf("?"));
}
}
if (format.equals(Format.UI)) {
if (!isEnabled() || !getOptionsParamApi().isUiEnabled()) {
throw new ApiException(ApiException.Type.DISABLED);
}
response = webUI.handleRequest(component, impl, reqType, name);
contentType = "text/html; charset=UTF-8";
} else if (name != null) {
if (!isEnabled()) {
throw new ApiException(ApiException.Type.DISABLED);
}
// Do this now as it might contain the api key/nonce
if (requestHeader.getMethod().equalsIgnoreCase(HttpRequestHeader.POST)) {
String contentTypeHeader = requestHeader.getHeader(HttpHeader.CONTENT_TYPE);
if (contentTypeHeader != null && contentTypeHeader.equals(HttpHeader.FORM_URLENCODED_CONTENT_TYPE)) {
params = getParams(msg.getRequestBody().toString());
} else {
throw new ApiException(ApiException.Type.CONTENT_TYPE_NOT_SUPPORTED);
}
}
if (format.equals(Format.JSONP)) {
if (!getOptionsParamApi().isEnableJSONP()) {
// Not enabled
throw new ApiException(ApiException.Type.DISABLED);
}
if (!this.hasValidKey(requestHeader, params)) {
// An api key is required for ALL JSONP requests
throw new ApiException(ApiException.Type.BAD_API_KEY);
}
}
ApiResponse res;
switch(reqType) {
case action:
if (!getOptionsParamApi().isDisableKey()) {
if (!this.hasValidKey(requestHeader, params)) {
throw new ApiException(ApiException.Type.BAD_API_KEY);
}
}
ApiAction action = impl.getApiAction(name);
if (action != null) {
// Checking for null to handle option actions
List<String> mandatoryParams = action.getMandatoryParamNames();
if (mandatoryParams != null) {
for (String param : mandatoryParams) {
if (!params.has(param) || params.getString(param).length() == 0) {
throw new ApiException(ApiException.Type.MISSING_PARAMETER, param);
}
}
}
}
res = impl.handleApiOptionAction(name, params);
if (res == null) {
res = impl.handleApiAction(name, params);
}
switch(format) {
case JSON:
response = res.toJSON().toString();
break;
case JSONP:
response = this.getJsonpWrapper(res.toJSON().toString());
break;
case XML:
response = this.responseToXml(name, res);
break;
case HTML:
response = this.responseToHtml(name, res);
break;
default:
break;
}
break;
case view:
if (!getOptionsParamApi().isDisableKey() && !getOptionsParamApi().isNoKeyForSafeOps()) {
if (!this.hasValidKey(requestHeader, params)) {
throw new ApiException(ApiException.Type.BAD_API_KEY);
}
}
ApiView view = impl.getApiView(name);
if (view != null) {
// Checking for null to handle option actions
List<String> mandatoryParams = view.getMandatoryParamNames();
if (mandatoryParams != null) {
for (String param : mandatoryParams) {
if (!params.has(param) || params.getString(param).length() == 0) {
throw new ApiException(ApiException.Type.MISSING_PARAMETER, param);
}
}
}
}
res = impl.handleApiOptionView(name, params);
if (res == null) {
res = impl.handleApiView(name, params);
}
switch(format) {
case JSON:
response = res.toJSON().toString();
break;
case JSONP:
response = this.getJsonpWrapper(res.toJSON().toString());
break;
case XML:
response = this.responseToXml(name, res);
break;
case HTML:
response = this.responseToHtml(name, res);
break;
default:
break;
}
break;
case other:
ApiOther other = impl.getApiOther(name);
if (other != null) {
// Checking for null to handle option actions
if (!getOptionsParamApi().isDisableKey() && (!getOptionsParamApi().isNoKeyForSafeOps() || other.isRequiresApiKey())) {
// Check if a valid api key has been used
if (!this.hasValidKey(requestHeader, params)) {
throw new ApiException(ApiException.Type.BAD_API_KEY);
}
}
List<String> mandatoryParams = other.getMandatoryParamNames();
if (mandatoryParams != null) {
for (String param : mandatoryParams) {
if (!params.has(param) || params.getString(param).length() == 0) {
throw new ApiException(ApiException.Type.MISSING_PARAMETER, param);
}
}
}
}
msg = impl.handleApiOther(msg, name, params);
}
} else {
// Handle default front page, unless if the API UI is disabled
if (!isEnabled() || !getOptionsParamApi().isUiEnabled()) {
throw new ApiException(ApiException.Type.DISABLED);
}
response = webUI.handleRequest(requestHeader.getURI(), this.isEnabled());
format = Format.UI;
contentType = "text/html; charset=UTF-8";
}
}
logger.debug("handleApiRequest returning: " + response);
} catch (Exception e) {
if (!getOptionsParamApi().isReportPermErrors()) {
if (e instanceof ApiException) {
ApiException exception = (ApiException) e;
if (exception.getType().equals(ApiException.Type.DISABLED) || exception.getType().equals(ApiException.Type.BAD_API_KEY)) {
// Fail silently
return true;
}
}
}
handleException(msg, format, contentType, e);
error = true;
}
if (!error && !format.equals(Format.OTHER) && shortcutImpl == null) {
msg.setResponseHeader(getDefaultResponseHeader(contentType));
msg.setResponseBody(response);
msg.getResponseHeader().setContentLength(msg.getResponseBody().length());
}
if (impl != null) {
impl.addCustomHeaders(name, reqType, msg);
}
httpOut.write(msg.getResponseHeader());
httpOut.write(msg.getResponseBody().getBytes());
httpOut.flush();
httpOut.close();
httpIn.close();
return true;
}
use of net.sf.json.JSONObject in project summer-bean by cn-cerc.
the class RemoteService method exec.
@Override
public boolean exec(Object... args) {
if (args.length > 0) {
Record headIn = getDataIn().getHead();
if (args.length % 2 != 0)
throw new RuntimeException("传入的参数数量必须为偶数!");
for (int i = 0; i < args.length; i = i + 2) headIn.setField(args[i].toString(), args[i + 1]);
}
String postParam = getDataIn().getJSON();
String url = String.format("http://%s/services/%s", this.host, this.service);
if (token != null)
url = url + "?token=" + token;
try {
log.debug("datain: " + postParam);
// String rst = CURL.doPost(url, params, "UTF-8");
String rst = postData(url, postParam);
log.debug("datatout:" + rst);
if (rst == null)
return false;
JSONObject json = JSONObject.fromObject(rst);
if (json.get("message") != null) {
this.setMessage(json.getString("message"));
}
if (json.containsKey("data")) {
JSONArray datas = json.getJSONArray("data");
if (datas != null && datas.size() > 0) {
if (dataOut == null)
dataOut = new DataSet();
else
dataOut.close();
dataOut.setJSON(datas.getString(0));
}
}
return json.getBoolean("result");
} catch (Exception e) {
log.error(e.getMessage(), e);
if (e.getCause() != null)
setMessage(e.getCause().getMessage());
else
setMessage(e.getMessage());
return false;
}
}
use of net.sf.json.JSONObject in project summer-bean by cn-cerc.
the class SAPIMessage method checkRegister.
/**
* 检查新用户请求的简讯代码是否正确
*
* @param mobile
* 手机号
* @param verifyCode
* 检验码
* @return 返回是否执行成功
*/
public boolean checkRegister(String mobile, String verifyCode) {
Map<String, String> params = new HashMap<>();
params.put("ip", getRemoteIP());
params.put("mobile", mobile);
params.put("verifyCode", verifyCode);
try {
String result = doPost(String.format("%s/forms/message.checkRegister", getHost()), params);
JSONObject json = JSONObject.fromObject(result);
if (json.has("result")) {
this.setMessage(json.getString("message"));
return json.getBoolean("result");
} else {
this.setMessage(result);
return false;
}
} catch (Exception e) {
e.printStackTrace();
this.setMessage(e.getMessage());
return false;
}
}
use of net.sf.json.JSONObject in project summer-bean by cn-cerc.
the class SAPISecurity method register.
/**
* 向聚安平台注册用户所关联手机号
*
* @param user
* 用户账号
* @param mobile
* 手机号
* @return true:成功,若失败可用getMessage取得错误信息
*/
public boolean register(String user, String mobile) {
Map<String, String> params = new HashMap<>();
params.put("ip", getRemoteIP());
params.put("user", user);
params.put("mobile", mobile);
try {
String result = doPost(String.format("%s/forms/security.register", getHost()), params);
JSONObject json = JSONObject.fromObject(result);
if (json.has("result")) {
this.setMessage(json.getString("message"));
return json.getBoolean("result");
} else {
this.setMessage(result);
return false;
}
} catch (Exception e) {
e.printStackTrace();
this.setMessage(e.getMessage());
return false;
}
}
Aggregations