Use of Hard-coded Password [CWE - 259] - java

While checking my veracode issue, i found this CWE 259 Use of Hard-coded Password in one of my class file. while checking that file, the 1st line of the file is responsible to this vulnerability, which is my package name. Can any one tell me why this is occurring or is this some flaw with veracode scan logic.
Inside this class file they are some place where word "password" is printed. as a precaution i tried by commenting those lines and scan it again. but the issue was thrown on the same line.
package com.name.ta.etc.cse;

The page for CWE 259 at MITRE specifies exactly what the vulnerability means and provides example of it, as well as suggest ideas in order to correct or mitigate the vulnerability in your application.
Code inspection tools like Veracode or SonarQube can also flag false positives (they detect the vulnerability, but it isn't there). I had a case with Sonar flagging this issue where I had a static final variable (ie: a constant) with the word PASSWORD in its name and Sonar thought it was the actual password, when in reality it was the key to find the password from the properties.
From your description, it might be the case here (extreme conditional, as you don't provide near enough code to judge). If you can refactor your code by changing the word password to any other, without changing the underlying logic, nor breaking incoming or outgoing authentication, then that's most likely the case here.

There is no flaw in veracode. Its scanning correctly. if it will find any keyword like "pass" or "paswd" or "password" it will raise it as "Flaw" so you have to mandatory remove/replace these kind for keyword to resolve it.
Remove/Replace the keyword scan your application again and check.
There is no real security concern until you are not storing password as plain text.

Related

VERACODE: CRLF Neutralization Warnings for Cookies - JAVA

recently after scanning our project we can across with Veracode warnings on CRLF neutralization. please find my error code below.
Cookie[] c = request.getCookies();
c[i].setValue("");
c[i].setMaxAge(0);
getting the issue on below line
response.addCookie(c[i]);
Solutions Tried:
1.setValue("") tried replacing with \r or \n
2. used Encode.forJava(String)
3. Used ESAPI, but our project is running on Java 1.6. No suitable ESAPI jar was found.
Any recommendations here? am I missing anything? Am I going in the wrong direction? Can anyone help me with this?
I don't think output encoding is the right approach here. Unless you are rendering the cookie name and/or value, the issue is not XSS, but rather HTTP Response Splitting.
Strict allow-listing is the best approach, here but if find that impossible (because you are not sure what the allowed values are supposed to be, which might be the case if you were writing an HTTP library or getting values from downstream processes, etc.), then go with block-list data validation. For the block-list approach, I recommend either outright rejecting any cookie containing ':', '=', '\r', or '\n' (and log an appropriate error) and redirect the user to any appropriate error page. Alternately, if you detect anything in the block list, you could simply ignore those values by just silently stripping them out (although you many want to log them).

Password sanitization within stacktraces & errors

We're currently running into an interesting problem regarding the sanitization of error logs being printed into our server logs. We have proper global error handling set up and have custom error messages that are sent back as responses from our OSGi java servlets.
We use dockerized containers as server instances that are autoscaled, so we're thinking about setting up a log aggregator and storing our exceptions within a DB in the cloud, that way we can also track metrics about our exceptions and pinpoint how we could improve our development process to reduce certain types of errors, etc.
I did a bit of research about how that should be done and I found this. The OWASP Logging sheet cheat. It mentions that passwords should never be logged among a few other things. That brings us to my question:
How do I go about properly sanitizing my logs without using some janky text processing or manually covering up all the potential cases?
Example stacktrace:
pkg.exceptions.CustomException: some registration error
ERROR: duplicate key value violates unique constraint "x_username_org_id_key"
Detail: Key (username, org_id)=(SOME EMAIL, 1) already exists.
Query: with A as (some query) insert into someTable (..values...) Parameters: [X, X, X, X, X, SOME_EMAIL, THE_PASSWORD]
at somepkg.etc
This is a pretty common error with registration systems that happens due to username collisions. Sure there's ways that this specific case can be avoided by ensuring the username isn't taken before the insertion isn't attempted and handling that case separately, but that's just a single case among many others.
After looking around to find a solution there doesn't seem to be an obvious way to solve the problem and I'm wondering if everyone out there has simply implemented their own version of a log sanitizer? We could simply purge the stacktrace if some troublesome strings are present, but that's not the best solution. Any suggestions?
If you only store and pass around password hashes you won't need to sanitize the logs for passwords. In cases where a password must be preserved temporarily in code use char[]s rather than Strings. This is a more secure approach in general and is considered a best practice. The standard library APIs all use character arrays for passwords.

how to ignore ESAPI exception "org.owasp.esapi.errors.IntrusionException: Input validation failure"?

My project (built on JSP,Struts,hibernate) takes an input from user and saves it in the database. To make my application secure I have used ESAPI jar.
I am getting exception
org.owasp.esapi.errors.IntrusionException: Input validation failure
at the method ESAPI.encoder().canonicalize();
This exception is generally coming when we are copying and pasting data from skype,MS word etc.
When I copy paste the string from skype messenger it automatically adds extra styling data with div,meta,p,etc (all the HTML tags) which leads to addition of many special characters which might be causing the exception mentioned above.
But when I copy the string from notepad it doesn't give an exception.
How can I ignore this exception so that I can add the data ? is there something to be modified in ESAPI.properties or validation.properties? what are your views?
I think your weird issue has to do with additional encoding when you paste something from (say) MS Word versus from something simple like notepad. When you are in Word, it picks up some additional meta-data and the default 'paste' from 'MS Word' is really 'paste special'. This is done so that you can copy text from one Office application to another (e.g., Word to Outlook) and "retain formatting". I think it is all this additional meta-data that you are getting that is messing you up, because it probably looks to ESAPI like it is multi-encoded or it thinks that mixed-encoding is used.
That said,if you want to do validation, you really ought to be using one of the Validator.isValidInput() or Validator.getValidInput() methods. This call Encoder.canonicalize() by default (unless you use the latest ESAPI from the 'develop' branch, where you can actually disable the canonicalization--a recent bug fix).
-kevin

How to validate a filename in JAVA to resolve CWE ID 73(External Control of File Name or Path) using ESAPI?

I am facing this security flaw in my project at multiple places. I don't have any white-list to do a check at every occurrence of this flaw. I want to use ESAPI call to perform a basic blacklist check on the file name. I have read that we can use SafeFile object of ESAPI but cannot figure out how and where.
Below are a few options I came up with, Please let me know which one will work out?
ESAPI.validator().getValidInput() or ESAPI.validator().getValidFileName()
Blacklists are a no-win scenario. This can only protect you against known threats. Any code scanning tool you use here will continue to report the vulnerability... because a blacklist is a vulnerability. See this note from OWASP:
This strategy, also known as "negative" or "blacklist" validation is a
weak alternative to positive validation. Essentially, if you don't
expect to see characters such as %3f or JavaScript or similar, reject
strings containing them. This is a dangerous strategy, because the set
of possible bad data is potentially infinite. Adopting this strategy
means that you will have to maintain the list of "known bad"
characters and patterns forever, and you will by definition have
incomplete protection.
Also, character encoding and OS makes this a problem too. Let's say we accept an upload of a *.docx file. Here's the different corner-cases to consider, and this would be for every application in your portfolio.
Is the accepting application running on a linux platform or an NT platform? (File separators are \ in Windows and / in linux.)
a. spaces are also treated differently in file/directory paths across systems.
Does the application already account for URL-encoding?
Is the file being sent stored in a database or on the system itself?
Is the file you're receiving executable or not? For example, if I rename netcat.exe to foo.docx does your application actually check to see if the file being uploaded contains the magic numbers for an exe file?
I can go on. But I won't. I could write an encyclopedia.
If this is across multiple applications against your company's portfolio it is your ethical duty to state this clearly, and then your company needs to come up with an app/by/app whitelist.
As far as ESAPI is concerned, you would use Validator.getValidInput() with a regex that was an OR of all the files you wanted to reject, ie. in validation.properties you'd do something like: Validator.blackListsAreABadIdea=regex1|regex2|regex3|regex4
Note that the parsing penalty for blacklists is higher too... every input string will have to be run against EVERY regex in your blacklist, which as OWASP points out, can be infinite.
So again, the correct solution is to have every application team in your portfolio construct a whitelist for their application. If this is really impossible (and I doubt that) then you need to make sure that you've stated the risks cited here clearly to management and you refuse to proceed with the blacklist approach until you have written documentation that the company chooses to accept the risk. This will protect you from legal liability when the blacklist fails and you're taken to court.
[EDIT]
The method you're looking for was called HTTPUtilites.safeFileUpload() listed here as acceptance criteria but this was most likely never implemented due to the difficulties I posted above. Blacklists are extremely custom to the application. The best you'll get is a method HTTPUtilities.getFileUploads() which uses a list defined in ESAPI.properties under the key HttpUtilities.ApprovedUploadExtensions
However, the default version needs to be customized as I doubt you want your users uploading .class files and dll to your system.
Also note: This solution is a whitelist and NOT a blacklist.
The following code snippet works to get past the issue CWE ID 73, if the directory path is static and just the filename is externally controlled :
//'DIRECTORY_PATH' is the directory of the file
//'filename' variable holds the name of the file
//'myFile' variable holds reference to the file object
File dir = new File(DIRECTORY_PATH);
FileFilter fileFilter = new WildcardFileFilter(filename);
File[] files = dir.listFiles(fileFilter);
File myFile = null ;
if(files.length == 1 )
myFile = files[0];

Log forging issues in fortify report

I have generated a Fortify report for my application. In a Fortify report it is showing Log forging issues in the below code:
holDate = ((MaintainHolidayCalenderForm) form).getCALENDER_DATE();
logger.info("This is some description" + holDate + holName );
and as per some people's suggestions I have replaced the "/n" with "" and "/r" with "" but still the issue is not resolved.
Can any one tell me how to resolve this?
Thanks in advance.
A blacklist fix, e.g. stripping out the log clearing characters (/n /r), still leaves an opportunity for an attacker to do malicious things with your application. If the holDate and holName are submitted from the browser they are UTF-8 strings, which can be very long and have any characters in the rather large UTF-8 unicode character set. If the log is usually viewed with an HTML viewer (common) an example attack might go like this: the attacker could forge a record that shows that they logged out, do their bad stuff, then write a log message that overwrites that activity using any of the unicode characters that cause backspaces or dels back to the 'friendly attacker logged out - nothing to see here' message. (Note: you should never try to predict how an attacker might affect bad things so don't try to blacklist all of the ways to get backspace characters in unicode.)
Rather than blacklisting, you should ensure that the data you're writing to the log is the type you expect, also known as whitelist validation, and of a reasonable length.
So the fix (in the code that you posted):
1. Make sure holDate is a Date object (java.util.Date) if it isn't already.
2. HolName is probably an alphanumeric string of a relatively small length. Choose a small length (like 30 characters) and make sure that only alphanumeric characters are accepted in the holName.
You can use a regex String.matches("^[a-zA-Z0-9]*$") after checking length to ensure that you're only accepting alphanumeric characters.
You should probably do this whitelist input validation in the setters for the form pojos.

Categories

Resources