Sonar violation properly sanitized before use in this OS command - java

In my project i got a sonar security violation-properly sanitized before use in this OS command. I have done the pattern check for my inputs, but still the violation is not going away.
if(Pattern.matches("[0-9]+", empNp)){
ProcessBuilder processBuilder = new ProcessBuilder(exeLoc, folderPath, empNp);
It still keeps complaining the empNp is not properly sanitized. Could you please let me know how to handle this. I cannot hard code the empNp because it is dynamic input.How to handle this.

The point of many of the security rules is to draw attention to something that requires human intelligence to determine whether or not the code is truly safe. If you're sure the input has been properly sanitized, then mark this issue False Positive and move on with a clear conscience.

Related

Catching java exception in Jython

I have an exception I'm trying to catch whenever my VNC connection is killed (whenever I restart my VM) and I'm trying to ignore it to continue my Jython script. I'm not sure how to write a try catch statement to catch the exception since it's originating from Java. This is for a sikuliX script.
Exception in thread "Thread-7" com.tigervnc.rdr.EndOfStream: EndOfStream
at com.tigervnc.rdr.FdInStream.readWithTimeoutOrCallback(FdInStream.java:192)
at com.tigervnc.rdr.FdInStream.overrun(FdInStream.java:142)
at com.tigervnc.rdr.InStream.check(InStream.java:37)
at com.tigervnc.rdr.InStream.check(InStream.java:44)
at com.tigervnc.rdr.InStream.check(InStream.java:45)
at com.tigervnc.rdr.InStream.readS8(InStream.java:55)
at com.tigervnc.rdr.InStream.readU8(InStream.java:64)
at com.tigervnc.rfb.CMsgReaderV3.readMsg(CMsgReaderV3.java:50)
at com.tigervnc.rfb.CConnection.processMsg(CConnection.java:67)
at org.sikuli.vnc.VNCClient.processMessages(VNCClient.java:246)
at org.sikuli.vnc.VNCScreen$1.run(VNCScreen.java:82)
at java.lang.Thread.run(Unknown Source)
#abarnert You really saved my day. I have encountered the same problem as OP posted. The jython code is as following:
################################################################
# CONFIG DEFINITIONS
################################################################
#GOOD_IMAGE_URL = "http://192.168.1.15/11111111.png"
BAD_IMAGE_URL = "http://192.168.1.15/111111112222.png"
def exceptionDemo(urlPath):
try:
print "exceptionDemo is starting"
myImg = imageio.ImageIO.read(URL(urlPath))
if myImg is None:
print "Img is None"
else:
print "Img is OK"
return myImg
#except Exception, err:
except java.lang.Exception as err:
print "Exception is here"
print err
finally:
print "Finally is here"
the purpose of this code is to download the image file specified by urlPath. when the ulrPath is bad(in this case, the 111111112222.png does not exist.), I would like to catch the exception in order to handle this issue properly.
If I simply use the normal "except Exception, err" to catch the exception, the program will just abort without any information. The print statements in except and finally section are supposed to execute, however, that didn't happen. What I get is nothing after seeing "exceptionDemo is starting".
I spent days on dealing with this problem, searching on google again and again, leaving no stone unturned. After days of investigation, I get the idea that there are two sorts of exceptions when you programming in jython, one is python exception, the other is java exception. The reason for this problem is that either jython or SikuliX in this case, has suppressed the java throwables. I am not very familiar with jython, so it's just my guess and it has not been verified(I am more familiar with native Python and Java).
At first, I doubt it's ImageIO - the native java package's problem. I wrote a simple java demo to test ImageIO by giving the bad image url, it worked great, a nice "javax.imageio.IIOException: Can't get input stream from URL" had been thrown out. Then, I know that my guess is right. The java exception somehow did not well handled in jython or SikuliX. The point here is that even if this is the root cause, I still need a simple and elegent way to deal with this problem. I tried some other workarounds, but nothing is as good as I've expected. The essential part of this problem is not about downloading the image, it's about catching the exception.
It was not until I simply replace "except Exception, err“ with "except java.lang.Exception as err" that the code is working like a charm. I got all the printouts that I expected.
Your posts really saved my day. Good job and many thanks.
The following references are very helpful in my investigation:
javax.ImageIO methods fail silently
trap exceptions comprehensively in Jython
https://www.jython.org/jythonbook/en/1.0/ExceptionHandlingDebug.html
Finally, If there were any tips I would like to offer to people who find this post, it should be "STAY AWAY FROM THIS KIND OF HALF-BAKED SHODDY HYBRID LANGUAGE", You will get neither the expediency of Python, nor the robustness of Java, the only thing that you eventually will get is a big waste of your time.
=================================================================
Update on 2019-08-02:
As a follow-up of this post, I offer you a "buy one get more free" deal. It contains a heck of surprise brought you by Jython and Sikuli X.
1, DO NOT USE ANYTHING DEPENDS ON Netty in Jython. This includes httplib and urllib2, etc. It will fail if you try to GET/POST something in a loop, use Requests or java.net instead.
for details, please refer to this post: Why does this Jython loop fail after a single run?
2, DO NOT USE type() function in Sikuli X. This function is normally used in python to determine the type of an object, however, Sikuli X use it to mimic the keyboard input function. If you insist, you should import builtin first, then call it like this:
# -*- encoding: utf-8 -*-
import __builtin__
if __name__ == '__main__':
a=10
print __builtin__.type(a)
for details, please refer to these:
How to check variable type using “type” function in Sikuli
https://answers.launchpad.net/sikuli/+question/239574
These are some pitfalls that I have experienced in jython and Sikuli X, if you have to work with these two things, good luck and wish you have fun.
As explained in Exception Handling and Debugging, you handle Java exceptions in Jython the same way you handle Python exceptions:
As stated previously, it is a common practice in Jython to handle Java exceptions. Oftentimes we have a Java class that throws exceptions, and these can be handled or displayed in Jython just the same way as handling Python exceptions.
A Java exception is, as far as your code is concerned, just an instance of some Exception subclass.
Of course that subclass happens to live in, e.g., java.lang instead of builtins or another stdlib module, and it will (almost?) always have java.lang.Exception as an intermediate ancestor before getting all the way back to Exception, but generally, you don't care about that.
So, wherever you're calling the Java code that's throwing this exception… just put a try: / except Exception as e: or except java.lang.Exception as e: or more specific type, the same way you would when calling Python code.

Java security vulnerability OS Injection Veracode

I receive a Veracode error when running the static scan: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') (CWE ID 78)
The application calls a process with an argument that I receive from the frontend (the application is used internally and this is a userId) .
ProcessBuilder pb = new ProcessBuilder(PROCESS, "-A", argument);
Process p = pb.start(); // Veracode is mentioning this line
How could I manage to fix this Veracode issue ?
Is there a 'safe' way to run a process?
Presumably your userId has a well defined format (numbers, hexadecimal digits, alphanumeric, ...), perhaps it is always the same length.
You have to verify it by matching userId to the appropriate class of characters via regex, and reject anything which is not complying, otherwise, you are open to the following attack:
Enter Username: diginoise; rm -rf /
Sounds like it's an architectural problem in your application. I'm pretty sure you don't want to execute a supposed userid passed by the user as a request parameter as an OS command. This would be OS command injection by design.
The ideal solution would be to avoid creating a new OS process and use built-in Java functionality to achieve your goal.
If you do have to run an external process, do not include user input into what you are running. For example if you had the static string ps aux to run and would do the "grep" bit in Java, the Veracode finding would go away and it would be a lot more secure.
If you absolutely must include user input, make sure it is very strictly validated. Note that for OS command injection, letters only may sometimes be enough, and Veracode will correctly flag that as vulnerable, despite validation being in place. In this case, if you are sure that with your validations, it is not possible to run anything malicious, you can mark the finding in Veracode as "mitigated by design".

Is it a good practice to log line number in error code to the user?

I have been tasked with logging the line number as part of the error code shown to the user. Currently I am using:
StackTraceElement[] stackTraceElement = e.getStackTrace();
lineNumber = stackTraceElement[0].getLineNumber();
I know that the above approach may fail depending on the JVM version.
Also, I have seen the PatternLayout where it is mentioned that "Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.".
Since this message will be presented to the user, should I still log the line number as part of the error code? I am trying to understand the pros and cons of this approach. Also, does the log4j warning apply only to its own implementation or rather is it a warning against location information generally?
Well, generally speaking your program should report two kind of errors:
The errors that are for the user (when the user is not doing what is expected from him), which should actually be better called "feedback" to help him feed your program with the right data (that's good UX practice).
The errors that are generated because of a bug, which are actually not targeted at the user, but at you the developer, sadly through the user. Then yes, it might be a good idea to log line numbers (or give your errors unique names/identifiers so that you can trace easily where it's been sent from). But a better idea is to then use a framework to report such issues directly to you through Internet (good practice being to ask for permission first).
What you should show to the user is what went wrong and what he can do about it, if anything. The line number information needs to be available, e.g. via a 'More details' button, in case he needs to raise a support ticket, but you don't want to frighten him or confuse him with it up front. Just look at how many stack traces get misread or indeed ignored completely here, and this community is supposed to be computer programmers.
Generally its better if your program doesn't give errors, and can receive all input, and give you tips on how to use the application. This will give users a much better experience if you want them to buy your product, etc.. If your program does give errors, it will not be helpful for the user to know the line number. You however will want to know the line number, so you should make it display a message of some sort that tells the user to email you the stack trace when the error occurs. Or you could have it report the error message automatically and email it to you.
Sorry, I'm a bit late I was unclear what the question was asking, so I posted this as a comment, but clearly it is an acceptable answer.

Search and replace if statements without braces to include braces

I've been recently using sonar for code analysis. When I go thorough violation drilldown, I found many java files with if statement defined without braces (thousands of places). Is there a simple way to replace or add braces to if statements or what are the steps that I can perform to achieve this task without doing it manually in each of the files.
I'm currently using intelliJ.
Is there a simple way to replace or add braces to if statements or what are the steps that I can perform to achieve this task without doing it manually in each of the files.
I don't know if there is a tool to do this automatically. (There probably is ...) But assuming that such a tool exists, I'm not convinced it would be the right approach.
Step back for a moment and consider why the code analysis has reported this as a problem. A lot of people (like #pst and me) think that the braces always should be there, even though various style guides don't insist on this. There is a good reason for this ... apart from "it looks ugly". Consider these example code snippets:
if (i == 1)
i++;
doSomething();
while (i < 1)
i++;
doSomething();
If you don't read those carefully, your eyes will trick you into thinking that doSomething(); is called conditionally ... due to the incorrect indentation. And it happens.
(Aside: labelling someone as "inept" for misreading that code is not helpful. If you are desperately trying to fix a show-stopper bug and you've been working for 14 hours straight, then you are likely to miss this kind of thing. And not because you are inept. Once you've been in that situation a couple of times, the lesson sinks in ...)
OK, now suppose that you run an automatic tool to add the braces. What you will get is this:
if (i == 1) {
i++;
}
doSomething();
while (i < 1) {
i++;
}
doSomething();
It means exactly the same thing as the original code. BUT ... what if the original code was actually a bug? What if the programmer intended the doSomething() calls to be conditional?
In short, by adding the braces automatically, we've obscured the original programmer's intention, and made these bug(s) harder to track down.
Bottom line - I think it would be prudent to manually review each of these occurrences ... rather than just "fixing" them automatically. Indeed, I'd argue that if you don't have the time or patience to review them manually, it would be better to leave the code alone. It would be better to turn off the warning ... IMO.
I can reformat the code to make intelliJ do the thing for me, but I need to go through all the files and reformat it. Yes, I might turned off the check but wondering if there is a good tool to do the task. I've good set of tests to check whether it introduce bugs during the process.
If you are sure that you have some ways to test that you will not introduce bugs then use the IntelliJ Reformat Code feature.
Just make sure that the Code Style you have in IntelliJ is in line with your company's policies. Otherwise you will force your style on everybody else too.
To force braces just mark them as Always on the Wrapping and Braces tag in the Code Style settings dialog in IntelliJ.
Mark the source folder in the project view and press Ctrl-Alt-L. A dialog pops up and there you can chose All files in directory <...>.
Then press Run and see what happens. If you are not satisfied then just revert from your VCS.
IntelliJ IDEA has an inspection for this as well, and it has a quick fix to automatically add the braces.
Invoke Analyze | Run Inspection by Name and enter inspection name Control flow statement without braces. Run it on the desired part of your project. In the inspection results you can apply the quick fix Add braces to statement.
Note that this inspection will also report control flow statement other than if, like for example while statements. Invoking the quick fix will also add braces to those statements.

java: check if a file can be moved under windows

I need to rename a file (keeping it in the same directory);
I can't seem to find a way to see if my program has the required permissions:
Files.isWritable(directory) && Files.isWritable(oldFile);
always returns true, wether or not the running user has the permission to write the file (I guess they only check if the file is read-only, even if this violates the contract stated in the javadoc);
I'm not running under a security manager so I can't call
System.getSecurityManager.checkDelete(oldFile.toString());
I need to check if the renaming of several files will (probably) succeed so I can't just try and catch the exception.
Is there a way out? Obviously a portable solution would be lovable but I would settle for a windows-specific one...
Well, you can't check Windows ACLs that way. The "native" solution is fairly easy, since Windows supports transactions on the file system. Just call DeleteFileTransacted, and roll back the transaction if any one deletion fails.
If you're not using tranactions, then the second option is to first open handles with explicit DELETE desired access (DELETE is one of the standard WinNT access rights), denying any sharing. If and only if this succeeds for all files, delete them all with SetFileInformationByHandle(handle, FileDispositionInfo, &fdiObj, sizeof(fdiObj));
(The latter is not a transaction and may have Isolation issues as a result, which in turn affect Atomicity).
Try new SecurityManager().checkDelete(oldFile.toString()).
Just try to move it! If the move failed, you didn't have permissions, or something else went wrong.
This is a general principle. Don't try to foretell the future, guessing whether an impending operation will succeed. Try the operation. Otherwise you introduce all sorts of extra problems:
You might make the wrong test.
The condition might change between the test and the operation.
The operation usually returns an error or throws an exception anyway, which you have to write code to handle: why write it all twice?

Categories

Resources