I have a college assignment where I have to get a first, middle, and last name from the user, and their age, and give them a bank ID using the initials and whatnot. But that's not what I'm here to ask.
I wanted to have a little bit of fun with it, and make the "Imaginary Bank" accidentally tell the user that it's a scam! Then an Error will pop up and delete that accidental line of text, replacing it with the normal "We look forward to helping you!" line. All I need to know how to do is delete that line of text that starts with "At Imaginary Bank, we" Thanks!
System.out.println("Hello " + first_name + " " + last_name + ", greetings from the Imaginary Bank!");
System.out.println("To access your account, please use the following ID: " + first_init + middle_init + last_init + age);
System.out.println("At Imaginary Bank we look forward to scamming you and stealing your money!");
try
{
Thread.sleep(11000);
}
catch (InterruptedException e) {
e.printStackTrace();}
System.out.println("ERROR! ERROR! ERROR! ERROR! ERROR! ERROR! ERROR! ERROR! ERROR! ERROR! ERROR!");
try
{
Thread.sleep(3000);
}
catch (InterruptedException e) {
e.printStackTrace() ;}
System.out.println("We look forward to aiding you with your financial needs! - The IB Team");
According to this answer, you can print a backspace character using \b in the console using System.out.print. Therefore, for however many characters you have previously printed, print that many backspace characters.
Additionally, this answer for the same question suggests using the cls command to clear the console output entirely, however this forever binds your application to only operating systems that use that command (In this case Windows / Dos). In linux, for example, the command is clear...I'm sure you see the potential problem.
You can always print out backspace characters like this:
System.out.print("\b");
Just print out the same number of characters you would like to remove.
Check out How to delete stuff printed to console by System.out.println()? There is not a certain way to remove text from the output window but there is generally a way for each type of console window. Take your pick for what works best for your deployment.
Related
I get this issue with CheckMarx security scan:
Method exec at line 69 of
web\src\main\java\abc\web\actions\HomeAction.java gets user input for
the CNF_KEY_COSN element. This element’s value then flows through the
code without being properly sanitized or validated and is eventually
displayed to the user in method logException at line 905 of
web\src\main\java\gov\abc\external\info\ServiceHelper.java. This may
enable a Cross-Site-Scripting attack.
Line 69 of HomeAction.java:
String cosn = (String) request.getParameter(CNF_KEY_CON);
Line 905 in ServiceHelper.java just logs the error:
private static void logException(InfoServiceException exception, String message) {
String newMessage = message + ": " + exception.getMessageForLogging();
try {
log.error(newMessage, exception);
} catch (Exception e) {
// fallback to console
System.out.println("error logging exception ->");
e.printStackTrace(System.out);
System.out.println("exception ->");
System.out.print(newMessage);
if (exception != null) exception.printStackTrace(System.out);
}
}
Changed another block of code in HomeAction.java to:
if(cosn!= null && cosn.matches("[0-9a-zA-Z_]+")) {
...
}
But that didn't help. How do I validate/sanitize/encode Line 69. Any help is much appreciated.
Thanks
You can sanitise strings for XSS attacks using Jsoup there is a clean() method for this. You would do something like this to sanitise the input:
String sanitizedInput = Jsoup.clean(originalInput, "", Whitelist.none(), new OutputSettings().prettyPrint(false));
Checkmarx defines a set of sanitizers that you can check in the system.
Based on your source code snippets; i assume that;
i) you are appending 'cosn' to 'message'
ii) application is web-based in nature (in view of the request.getParameter)
iii) message is been displayed to the console or log to a file.
You could consider using Google Guava or Apache Commons Test to html escape the input.
import com.google.common.html.HtmlEscapers;
public void testGuavaHtmlEscapers(){
String badInput = "<script> alert me! <script>";
String escapedLocation = HtmlEscapers.htmlEscaper().escape(badInput);
System.out.println("<h1> Location: " + escapedLocation + "<h1>");
}
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
public void testHtmlEscapers(){
String badInput = "<script> alert me! <script>";
System.out.println(escapeHtml4(badInput));
}
I would also consider if there is sensitive information, that i should mask e.g., using String.replace.
public void testReplace(){
String email = "some-email#domail.com";
String masked = email.replaceAll("(?<=.).(?=[^#]*?.#)", "*");
System.out.println(masked);
}
Above 3 sanitization methods will work similarly.
This is likely a false positive (technically, "not exploitable" in Checkmarx) with regard to XSS, depending on how you process and display logs. If logs are ever displayed in a browser as html, it might be vulnerable to blind XSS from this applications point of view, but it would be a vulnerability in whatever component displays logs as html, and not in the code above.
Contrary to other answers, you should not encode the message here. Whatever technology you use for logging will of course have to encode it properly for its own use (like for example if it's stored as JSON, data will have to be JSON-encoded), but that has nothing to do with XSS, or with this problem at all.
This is just raw data, and you can store raw data as is. If you encode it here, you will have a hard time displaying it in any other way. For example if you apply html encoding, you can only display it in html (or you have to decode, which will negate any effect). It doesn't make sense. XSS would arise if you displayed these logs in a browser - in which case whatever displays it would have to encode it properly, but that's not the case here.
Note though that it can still be a log injection vulnerability. Make sure that whatever way you store logs, that log store **does* apply necessary encoding. If it's a text file, you probably want to remove newlines so that fake lines cannot be added to the log. If it's json, you will want to encode to json, and so on. But that's a feature of your log facility, and not the code above.
I am writing a plugin which takes a message from discord and sends it to a minecraft server.
Minecraft clients have a hard time rendering emojis. Therefore I opted to use https://github.com/kcthota/emoji4j to convert all emojis into their shortcodes (example: đŸ˜ƒ -> :smile: ..or similar)
The problem:
When calling the static method shortCodify it never returns. Almost as if it kills the code where it is and never continues. No errors in console.
It almost seems as though calling the method kills it right there. Step 1 is never printed.
It is able to run through this multiple times (every time I send a discord message). It has not killed the process completely.
I have tried:
Adding the debug prints all over the place to try to track down the issue.
PS: don't hate me for mixing logger.info and system println, I am removing all of this later xD
Console output
13:35:48 [INFO] [Core] Emoji manager exists.
13:35:48 [INFO] [Core] Attempting shortcodify (contains 1738 emojis)
13:35:48 [INFO] DEBUG: EventChat.java step 0
Yes.... it stops there!
Code snippets:
My code / EventChat.java
Note: msg is a String
The if statement (of which you see the else) just checks that the emoji data was loaded, because I ran the config loading in a separate thread. Knowing it is able to get to here and prints that the data exists, this is not the problem.
...
} else {
logger.info("Emoji manager exists.");
try {
logger.info("Attempting shortcodify (contains " + EmojiManager.data().size() + " emojis)");
System.out.println("DEBUG: EventChat.java step 0");
msg = EmojiUtils.shortCodify(msg);
logger.info("new message: " + msg);
} catch (Exception e) {
logger.info("Catching exception");
e.printStackTrace();
}
}
logger.info("Emoji processed.");
Emoji4j / EmojiUtils.java
public static String shortCodify(String text) {
System.out.println("DEBUG: EmojiUtils.java step 1");
String emojifiedText = emojify(text);
System.out.println("DEBUG: EmojiUtils.java step 2");
for (Emoji emoji : EmojiManager.data()) {
StringBuilder shortCodeBuilder = new StringBuilder();
shortCodeBuilder.append(":").append(emoji.getAliases().get(0)).append(":");
emojifiedText = emojifiedText.replace(emoji.getEmoji(), shortCodeBuilder.toString());
System.out.println("DEBUG: EmojiUtils.java step 2.loop");
}
System.out.println("DEBUG: EmojiUtils.java step 3");
return emojifiedText;
}
I found the answer after what seems to be wayyy too long. (yes, 2 months lol)
NOTE: this only applies to anyone using JDA with emoji4j
JDA catches all Throwables by default and attempts to log it to the console but fails due to bungeecord not using the same logger (or something similar, I don't really know why).
I wasn't too stupid, as I tried catching all exceptions and logging them. BUT it was throwing a throwable instead of an exception.... for whatever reason...
So, long story short, I was catching excpetions and JDA was catching the Throwable that indicated the missing dependency and making the error vanish instead of printing to console.
Fix
try {
} catch (Throwable t) {
// error is now caught and can be logged using bungee's logger
}
The below code is being identified by Fortify as a vulnerability/issue of the "Privacy violation" category.
sbfOut.append(" validateSSN(document.form1." + name
+ ",\" \",\" \")' " + override + "; >");
out.println(sbfOut.toString());
} // SN end
else if (fieldType.equals(CoConstants.DE_ELEMENT_TYPE_TN
In another method I have, Fortify identified the below code block as a vulnerability issue of the "Privacy violation" category as well.
sbfOut.append(" <OPTION VALUE='0'>-NO DATA-</OPTION>");
try {
out.println(sbfOut.toString());
} catch (IOException ioe) {
debug("Exception In coCustomTag" + ioe
I am not able to figure out how to fix this and where exactly the issue is.
The exact message Fortify is giving:
The method methodName() in CoCustomTag.java mishandles confidential information, which can compromise user privacy and is often illegal.
Please ignore the open braces and all, as I have put here only the portion of code identified by Fortify.
If you believe that this issue is a false positive or u can ignore then
Fortify Java Annotations #FortifyNotPassword, #FortifyNotPrivate can be used to indicate which fields and variables represent passwords and private data.
These annotations will tell fortify code analyzer to ignore the fields and issue is gone.
Check below for more details.
HP Fortify -- annotating method parameters
If in your first code snippet HTML output is created and name can be changed by the user (e. g. by rewriting the URL) then this is a cross-site scripting (XSS) vulnerability issue: setting name to ," "," ");alert("Hi");// may cause popping up an alert box.
I was bothered for maybe three days or more, searching Google for any clue I could get, until I looked up into the stack trace on the bottom left of the Audit Workbench (in Fortify). The top of the stack trace suggested to me that my issue was caused by a method named decrypt(...). Believe it or not, when I renamed the method, the issue disappeared.
The following part of code raises a major bug at SonarQube :
"Invoke method(s) only conditionally."
How am I supposed to fix this?
if(us != null){
logger.info("Log this: {}", us.toString());
}
The call to us.toString() is redundant, toString() method will be called regardless the configured log level. You should pass only us as an argument to info without an if statement.
logger.info("Log this: {}", us);
As stated at the comments of the question, another working answer is:
if(logger.isInfoEnabled() && us != null){
logger.info("Log this: {}", us.toString());
}
You can just ignore this but it might be good to handle this scenario if possible, It would help us to handle and cutoff unnecessary computations.
One thing what it suggests here is to check if the Log Level that you are going to use is enabled or not.
if(logger.isInfoEnabled() && us != null){
// this inner code will only get executed if the above is true
logger.info("Log this: {}", us.toString());
}
Imagine having a complex task running inside, it would be a waste of time to do that if you are not going to log it anyways, if the log level is disabled. Logger will internally check that for you but doing it now before invoking the .info() will save you some cycles.
Passing message arguments that require further evaluation into a Guava com.google.common.base.Preconditions check can result in a performance penalty. That's because whether or not they're needed, each argument must be resolved before the method is actually called.
Similarly, passing concatenated strings into a logging method can also incur a needless performance hit because the concatenation will be performed every time the method is called, whether or not the log level is low enough to show the message.
Instead, you should structure your code to pass static or pre-computed values into Preconditions conditions check and logging calls.
Specifically, the built-in string formatting should be used instead of a string concatenation, and if the message is the result of a method call, then Preconditions should be skipped altogether, and the relevant exception should be conditionally thrown instead.
Noncompliant Code Example
logger.log(Level.DEBUG, "Something went wrong: " + message);
// Noncompliant; string concatenation performed even when log level too high to show DEBUG messages
logger.fine("An exception occurred with message: " + message);
// Noncompliant
LOG.error("Unable to open file " + csvPath, e); // Noncompliant
Preconditions.checkState(a > 0, "Arg must be positive, but got " + a);
// Noncompliant. String concatenation performed even when a > 0
Preconditions.checkState(condition, formatMessage()); // Noncompliant. formatMessage() invoked regardless of condition
Preconditions.checkState(condition, "message: %s", formatMessage());
// Noncompliant
Compliant Solution
logger.log(Level.SEVERE, "Something went wrong: {0} ", message);
// String formatting only applied if needed
logger.fine("An exception occurred with message: {}", message);
// SLF4J, Log4j
logger.log(Level.SEVERE, () -> "Something went wrong: " + message);
// since Java 8, we can use Supplier , which will be evaluated lazily
LOG.error("Unable to open file {0}", csvPath, e);
if (LOG.isDebugEnabled() {
LOG.debug("Unable to open file " + csvPath, e);
// this is compliant, because it will not evaluate if log level is above debug.
}
Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a); // String formatting only applied if needed
if (!condition) {
throw new IllegalStateException(formatMessage()); /
/ formatMessage() only invoked conditionally
}
if (!condition) {
throw new IllegalStateException("message: " + formatMessage());
}
Exceptions
catch blocks are ignored because the performance penalty is unimportant on exceptional paths (catch block should not be a part of standard program flow). Getters are ignored as well as methods called on annotations which can be considered as getters. This rule accounts for explicit test-level testing with SLF4J methods isXXXEnabled and ignores the bodies of such if statements.
It's related to performance issues. They recomend just putting a pure String or a final variable defined previously.
final var message = "Log this: " + us.toString();
logger.info(message);
https://sonarcloud.io/organizations/default/rules?languages=java&open=java%3AS2629&q=S2629
Short easy answer: just delete the .toString from your code since the formatter will take care of changing it to String for you.
I am working on a GA which used to work fine up until last week. In my efforts of optimizing the code I somehow broke the output sequence where the program dumps information about each generation of individuals. In all my debug efforts I came to understand that it's probably a flushing problem, but I can't really put my finger on the crux. The odd thing is that I actually did not touch any part of the IO since the last working version of the code.
The GA is part of a much larger software where there is a progress console which is essentially a way to "mirror" System.out and System.err to the GUI. From my debugging efforts I realized that the buffer does not flush even if I specifically call ps.flush().
What could be the reason of this problem??
Edit: To answer the questions in the comments, as well as further information on the problem:
The rest of the software does it's output to the GUI and Eclipse console as normal, it's only the calls to the outputGenInfo() method (see below) that have disappeared
If I add a notification line such as System.out.println("Fitness calculation is complete!"); in my evaluateGeneration() method which is called just before the outputGenInfo() the information for each generation gets printed exactly as expected... [That particular line was one of things I had trimmed during my optimization efforts]
For mirroring/redirecting System.out I used the MessageConsole class written by Rob Camick which can be found here
The suspicious code is as follows:
/**
* Convenience method for getting debug/info
* on this generation
* #param ps - a <code>PrintStream</code> to output to
* */
public void outputGenInfo(PrintStream ps){ // <-- ps = System.out by default
double stdev_fitness = stats.getStandardDeviation();
double mean_fitness = stats.getMean();
double cv = stdev_fitness / mean_fitness;
StringBuilder sb = new StringBuilder();
String new_line = System.getProperty("line.separator");
sb.append(new_line);
sb.append("+++++++++++++++++++++++++++++++++");
sb.append(new_line);
sb.append("Generation: " + this.id);
sb.append(new_line);
sb.append("-------------------------------");
sb.append(new_line);
sb.append("Mean fitness: " +
String.format("%.3f",mean_fitness) +
", CV: " + String.format("%.3f",cv));
sb.append(new_line);
sb.append("Top fitness: " + getTopIndividual().getEntropy());
sb.append(new_line);
sb.append("+++++++++++++++++++++++++++++++++");
sb.append(new_line);
ps.println(sb.toString());
// during debug this actually helps but not when the code is running full throttle!
System.out.println("");
}