Information Exposure Through an Error Message in checkmarx - java

try {
//code
} catch (ParseException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
LOG.error("Error in finding Resource Bundle", e);
}
I wrote like that, but when I am using Checkmarx code analysis tool I am getting "Information Exposure Through an Error Message". How to resolve and when this we get.

What is Information Exposure Through an Error Message?
The software generates an error message that includes sensitive information about its environment, users, or associated data.
The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack.
(Quote taken from CWE-209: Information Exposure Through an Error Message
)
You did not specify, but I'm assuming that the Checkmarx tool pointed to printStackTrace() as the problematic end point of the flow.
By using this method, an exception (including its entire stack trace) will be printed to the standard error stream. This might include information that may be sensitive by itself (like usernames or passwords) or at least disclose some environment data. If this data is exposed to a user, it can be abused or used maliciously for more effective attacks.
There are many others reasons not to use printStackTrace() that way, as can be seen here: Why is exception.printStackTrace() considered bad practice?

First of all remove e.printStackTrace();.
Now, As its compulsory to log errors so, you can;t remove LOG.error("Error in finding Resource Bundle", e);.
So, just provide the closure for this .. that Logs are being generated. As this is LOW critical their is no big issue.
This happens every-time with our project too :P .

Related

Why does squid:S1166 not accept exception messages only when logging caught exceptions?

Quote from the description of the rule (SonarQube 4.5.5):
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ }
catch (Exception e) { LOGGER.info(e.getMessage()); }
By providing the exception class to the logger a stack trace is written to the logs.
The problem in our code base is this:
By following the Tell, don't ask principle, we use checked exceptions as part of the, what we consider, normal execution paths and we don't want them to result in unreasonably large log messages.
A few examples: Servers responding with error codes, database statement executions failing on optimistic locking (concurrent users)...
My suggestion: Split this case in two.
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ }
catch (Exception e) { LOGGER.info(e.getMessage()); }
and
// Compliant - exception is lost (only message is preserved) but there is business logic handling the situation
try {
/* ... */
} catch (Exception e) {
LOGGER.info(e.getMessage());
*/ exception handling */
}
The rule squid:S00108 (code blocks must not be empty) would not catch the problem since there is a logging statement.
Is this not reasonable? Have I missed something of importance?
Note: I've rewritten the question to clarify my use case
I understand the arguments for maintaining the stack trace and all that, but I think it's going to bloat your logs for a < ERROR level event. One solution is to log the message as a WARN and log the exception object as DEBUG or TRACE. That way a normal user log config would not be flooded with business as usual stack traces, but it would still be possible to get a stack trace if necessary.
If it's causing hundreds of what you consider to be FP's then you should think about turning the rule off, or excluding it from your project files.
But to answer your question:
The point of exception logging is to leave enough information for investigators to figure out the cause of a problem.
If your messages are detailed, e.g.
The x in the y method broke because the frabjous was not day enough
then perhaps they fulfill that purpose. But what about a message like
Something went wrong
?
Further, you know exactly what each exception message means, but someday you'll presumably move on to bigger and better things. Will the next guy who supports the system have the same depth of knowledge? He may be grateful for the stacktraces and line numbers that tell him where to start looking...
But finally, I have to ask: why are you getting and logging so many exceptions that you flood the logger?
(Adding another answer to address the question as rewritten:)
Why would you both handle the exception and log it? If it's handled, there's no reason to log.
try to pass whole object to method than just a e.getMessage()LOGGER.info("INFO "e.);

Security: CWE-201: What is the correct way to securely read a properties file using openStream?

I'm working on coming up with a solution for CWE-201 that is flagged from Veracode.
Background:
CWE-201: Information Exposure Through Sent Data
Information Exposure Through Sent Data
Weakness ID: 201 (Weakness Variant) Status: Draft
+ Description
Description Summary
The accidental exposure of sensitive information through sent data refers to the transmission of data which are either sensitive in and of itself or useful in the further exploitation of the system through standard data channels.
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design and that the compartmentalization serves to allow for and further reinforce privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide when it is appropriate to use and to drop system privileges.
Besides...what the heck does that mean for people who code, I'm trying to find some practical solutions using java to resolve this problem.
What I can tell is that the following code will cause veracode to flag the cwe-201:
public void init(URL filePath) {
try {
load(new BufferedInputStream(filePath.openStream()));
} catch (java.io.IOException e) {
Log.error("Could not load server properties file!", e);
}
}
More information:
Phase: Implementation
Ensure that any possibly sensitive data specified in the requirements is verified with designers to ensure that it is either a calculated risk or mitigated elsewhere. Any information that is not necessary to the functionality should be removed in order to lower both the overhead and the possibility of security sensitive data being sent.
Phase: System Configuration
Setup default error messages so that unexpected errors do not disclose sensitive information.
I have done the recommendation stated in the System Configuration by creating a custom runtime exception which swallows the the IOException here...but Veracode still flagged it.
Here's that that code looks like:
public class CWE201Exception extends RuntimeException {
private static Logger log = ESAPI.getLogger(CWE201Exception .class.getName());
public CWE201Exception(String identifer, Throwable t){
log.error(Logger.SECURITY_AUDIT, identifer);
}
}
And updated the method to look like this:
public void init(URL filePath) {
try {
load(new BufferedInputStream(filePath.openStream()));
} catch (java.io.IOException e) {
throw new CWE201Exception("omgStillDoingThis", e);
}
}
Looking through the veracode report, I came across the following:
Attack Vector: java.net.URL.openStream
Description: The application calls the java.net.URL.openStream() function, which will result in data being transferred out of the application (via the network or another medium). This data contains sensitive information. openStream() was called on the filePath object, which contains potentially sensitive data. The potentially sensitive data originated from an earlier call to java.lang.system.getproperty.
Remediation: Ensure that the transfer of the sensitive data is intended and that it does not violate application security policy. This flaw is categorized as low severity because it only impacts confidentiality, not integrity or availability. However, in the context of a mobile application, the significance of an information leak may be much greater, especially if misaligned with user expectations or data privacy policies.
QUESTION
It turns out that when you read a property file that resides on your server in this way, you are using System.getProperties() indirectly.
Exposing this as a stream is viewed as the security threat
With that said, what is the correct way to load a property file so that your application can load environment configuration informationin what a manner that veracode considers a "safe"?

Java log levels - When to use What

When should i use below log levels? If there is any example that would be great.
Trace Vs Debug
Warn Vs Error Vs Fatal
WARN VS ERROR Vs FATAL
Will I need to use FATAL in my application code in first place?
I have never seen FATAL logging in any code still now in projects that i worked on till now.
I have read that, in case of FATAL program will end. If this is the case, I wonder how my log statement will execute.
Moreover, I think FATAL can not be used in the case of memory allocation as JVM will throw out of memory exception and exit the program. Hence developer can not log anything. If this is correct then where exactly i will use FATAL?
For ERROR and Warning:
In catch block, if I do not have a alternate logic (for error condition) to perform then, I will go and log exception with Error level, the exception will be transformed into user specific and displayed in screen.
At the same time, the Warn will be used when we have alternate flow /path to the exception logic.
For Debug
This will be to validate what and where the exception been thrown. What means the data that casued the error. Hence this can be used just before and after the complex logic of the code.
Please let me know if my understanding is correct
example:
class myLogLevel{
void method1( int empId)
{
log.trace("method1 starting") ;
try{
log.info("befor getting data from DB");
log.debug("executing the value for emp id : " + empId );
//DBConnection and code here
} catch (Exception1 e1) {
log.warn("record not found. So assigning default value");
// Code logic to assign default value
}
catch (Exception1 e1) {
// Due to DB connection error. Connection nor established
log.error("DB connection not established");
}
log.trace("method1 ending") ;
}
}
In my past experiences, a somewhat common practice is
Always use DEBUG for your debugging purpose. I seldom see people use TRACE.
For stuff which is bad for the system but not necessarily cause problem (i.e. if it's an error depends on the calling context), use WARN; E.g. you could write a function which sometimes return NaN; but NaN might not be an error for the caller depends on your context.
For stuff that's surely an error somewhere in the system or in the caller input data; that definitely needs human involvement (i.e. someone needs to look at it from your production support team), uses ERROR. E.g. you want to write a person's record into database but found the primary key (firstname, lastname) is NULL.
For stuff that would cause the entire system to shut down or cause seriously impact on the system, use FATAL. That means people needs to look at it immediately. Examples include problems that cause startup failure; memory allocation failure; A messaging processing system failed to initialize the messaging layer; etc.
Hope the above helps.

if every exception catch should log it?

some books mentioned that the followed mode is bad. It says every exception if be rethrowed shouldn't log it to avoid to dupliacte exception log.? any other issues?
I am confused that if I can't log any exception when rethrow it , if the issue exist?
or if I log it, I am confused if the too many log generated if everybody do it.
catch (NoUserException e) {
LOG.error("No user available", e);
throw new UserServiceException("No user available", e);
}
the reference
http://today.java.net/pub/a/today/2006/04/06/exception-handling-antipatterns.html#logAndThrow
I'm not sure about the books you mentioned, but to me, as someone who'll have to debug the code and find the root cause of the bugs, I'd like to read about it later in the logs as close as possible to the place where it first triggered.
Every LOG function have a switch to disable that log message so you have to LOG all exception if it is unexpected one. If you expected that exception, for example you check if the String is a number and you would like to know the result on exception, then you do not need to do the Log.
As far as exceptions are concerned, the most important log message should be located in service layer. Important thing is keeping the whole stack trace so the issue can be easily located even after several rethrows.
You can always put logs in all layers and manipulate logging level for certail layers to see only logs from layer you are currently debugging/working on. Other logs can be set to OFF. Read documentation for your favorite logger to learn more about that.

App Server Logs

What are some of the techniques / tools you use to analyze your application server logs?
My dev environment is Windows and my logs are on prod unix boxes .Some times I need to go thru archived logs(atleast on 4 servers) from many months ago to figure out a root cause of a error or exception. It is kind of a time consuming process and I want to hear from the community some of the best practices.
Thanks
If you have a large number of logs you could look at a log indexing/search solution. this would enable you to index you log files in real time and allow you to search via keywords for the data that you want. there's a product called Splunk that will be able to help you here:
http://www.splunk.com/
For open source versions see the following previous stackoverflow links:
What commercial and open source competitors are there to Splunk?
Apart from custom scripts there are a variety of tools to help you with this. Lots of very good paid for solutions are available.
One good open source option is chainsaw it's from the log4j developers and is apache licensed:
http://logging.apache.org/chainsaw/index.html
Take a step back and see if you have a log searching problem or an error reporting problem.
Does a single error result in multiple log entries or a single one? Do you have thousands of lines of info and debug messages for each error? Why are your logs so hard to search?
Without seeing your code; is it littered with the following?
} catch (Exception e) {
//error suppressed
log.error("error" + e.getMessage());
}
...
} catch (Exception e) {
//error logged and passed along
log.error("error" + e.getMessage());
throw e;
}
...
} catch (Exception e) {
//error logged and new one passed along
log.error("error" + e.getMessage());
throw new Exception("error" + e.getMessage());
}
The end result is that a single error can lead to multiple error log entries as the problem is logged and bounced rather than handled. I call this bureaucratic logging since all errors are filed in triplicate, passed around, and no one takes actual responsibility in handling the problem.
I would consider separating errors from info and debug messages and work to make reported bugs easier to find.

Categories

Resources