CheckMarx - Cross-Site-Scripting attack - java

I'm a newbie to the CheckMarx and preventing XSS attacks. I've got this error:
Method %> at line 1 of \app\src\web\searchresults.jsp gets user input for the getSearchResults 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 %> at line 1 of \app\src\web\searchresults.jsp. This may enable a Cross-Site-Scripting attack.
This is the line that it complaining about in the code snip below:
<c:forEach var="combo" items="${searchForm.searchResults}">
Code snip from a searchresults.jsp (code modified to protect the innocent)
<% int i = 0;%>
<c:forEach var="combo" items="${searchForm.searchResults}">
<tr <%=i++%2==0?"":"class='odd'"%>>
<td align="center" style="width: 40px;"><c:out value="${combo.stay.status}"/></td>
<c:choose>
<c:when test="${hasDetailAccess}">
<c:url var="detailLink" value="/detail.do">
<c:param name="code" value="${searchForm.code}"/>
<c:param name="brandCode" value="${searchForm.brandCode}"/>
<c:param name="smUni" value="${combo.object1.smUni}"/>
<c:param name="shUni" value="${combo.object1.shUni}"/>
<c:param name="searchType" value="${searchForm.searchType}"/>
</c:choose>
<td style="width: 80px;"><fmt:formatDate pattern="MMM dd yyyy" value="${combo.object1.dateMade.date}"/></td>
<td style="width: 80px;"><c:out value="${combo.object1.lastName}"/></td>
<td style="width: 80px;"><c:out value="${combo.object1.firstName}"/></td>
</c:forEach>
The part that I'm not for sure of how to fix is that the "searchForm.searchResults" is an queueCombo that can refer to multiple objects, for this instance, "object1".
My thought is to do the clean-up on the object. My method of doing this would be to add the needed attributes the page is using (as the "object1" is HUGE number of attributes) and put as single values and populate them when the object is constructed.

I don't have a specific solution for sanitizing your "queueCombo" after that it has been built, but generally the best-practices for securing the user inputs are:
as soon as the value is received from the user (early control): here before building your object. Most sanitizations made early intend to remove forbidden characters and control values formats. Eg: here the first and last names should not contain anything else than alphabetical characters.
You should not perform a transformation of variables early if the transformation aims to encode the data in a specific format (eg HTML output) because it could made the use of the objects in other contexts (eg: DB queries) harder to do.
just before using the variable (late control). Eg: SQL sanitization prior making a SQL query, or HTML encoding prior printing the values.
I think, in regards of your code snippet, that the latter should do.
Checkmarx is alerting on the loop line, but the issue is not really there. It lies in the value= statements that follow, the sanitization should be made here.
Tip for other readers: do not forget that any sanitization process should be made server side. If made client-side, it is mostly cosmetical.

Related

Struggling with MySQL and Netbeans

I need help implementing a MySQL database into Netbeans.
Basically, I've got two databases - one called Words, with 5,014 different words in and one called definitions with all the words definitions in.
I have implemented the Words database into a drop down list in NetBeans so that it presents all 5,014 words but I'm stumped as how to implement the other database so that when the user clicks, say for example, "Abandon" and the Submit button the resulting definition page will only display the definition for Abandon, which I have in the Definition database.
Here's my code for the opening page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Online English Dictionary</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1 align="center">Hello and welcome to my Online English Dictionary</h1>
<table align="center">
<thead>
<tr>
<th>This Online English Dictionary uses a 5,000 word list
compiled by Professor Mark Davies of Brigham Young University
in Provo, Utah.</th>
</tr>
</thead>
<tbody>
<tr>
<td>To view a definition of a particular word, please select
from the list below.</td>
</tr>
<tr>
<td>
<form action="submit.jsp">
<strong>Select a word:</strong>
<select name="word_id">
<c:forEach var="row" items="${words.rowsByIndex}">
<option><c:out value="${row[1]}"/></option>
</c:forEach>
</select>
<input type="submit" value="submit" name="submit" />
</form>
</td>
</tr>
</tbody>
</table>
</body>
While this is the code to create my Definition database:
DROP TABLE IF EXISTS Definition;
CREATE TABLE Definition (
definition_id SMALLINT,
definition VARCHAR (2500),
word_id VARCHAR (17),
PRIMARY KEY (definition_id),
FOREIGN KEY (word_id) REFERENCES Words(word_id)
);
INSERT INTO Definition (definition)
VALUES ('1. The first letter of the modern English alphabet.
2. Any of the speech sounds represented by the letter a.
3. The first in a series.
4. Something shaped like the letter A.
5. A The best or highest in quality or rank: grade A milk.
6. Music
a. The sixth tone in the scale of C major or the first tone in the relative minor scale.
b. A key or scale in which A is the tonic.
c. A written or printed note representing this tone.
d. A string, key, or pipe tuned to the pitch of this tone.
7. A One of the four major blood groups in the ABO system. Individuals with this blood group have the A antigen on the surface of their red blood cells, and the anti-B antibody in their blood serum.'),
('vb (tr)
1. to forsake completely; desert; leave behind: to abandon a baby; drivers had to abandon their cars.
2. (Nautical Terms) abandon ship the order given to the crew of a ship that is about to sink to take to the lifeboats
3. to give up completely: to abandon a habit; to abandon hope.
4. to yield control of or concern in; relinquish: to abandon office.
5. to give up (something begun) before completion: to abandon a job; the game was abandoned.
6. to surrender (oneself) to emotion without restraint
7. (Insurance) to give (insured property that has suffered partial loss or damage) to the insurers in order that a claim for a total loss may be made
n
8. freedom from inhibitions, restraint, concern, or worry: she danced with abandon.');
If anyone can help it would be great!
Thanks,
James
Well you would need to set that to the session and then in submit.jsp read this value and then fire another query.
That being said, I would like to recommend not to use jstl tags for SQL queries and use an MVC model instead where this can be easily taken care of.
Setting up the values in the controller and returning to the jsp.
onChange of the dropdown - fire an ajax request to get the details.
Show the details then and there in a separate div without navigating to other pages.
If you would still like to continue with jstl here is a great tutorial if you have some time.
For MVC with JSP, you can check out couple of tutorial links : here and here.
HTH.

Spring MVC Application combine form using GET method and URL with path Varibles

I am developing an MVC web app using spring framework.
At some point I have a jsp that is listing study case objects as sown below
<tbody>
<c:forEach items="${studycases}" var="studycase">
<tr>
<td>
<a href='<spring:url value="/studycase/${studycase.study_case_number}.html"/>'>
${studycase.study_case_number}
</a>
</td>
<td>
${studycase.dateOFHospitalAdmission}
</td>
<td>
${studycase.dateOfWardAdmission}
</td>
<td>
${studycase.dateOfWardDischarge}
</td>
</tr>
</c:forEach>
</tbody>
as you can see there is a spring:url that is directing to a jsp with details about the spesific study case, that is being handled by the below controller :
#RequestMapping("/studycase/{studyCaseNumber}")
public String detail(Model model, #PathVariable String studyCaseNumber)
{
model.addAttribute("studyCase", studyCaseService.findOne(studyCaseNumber)) ;
model.addAttribute("measurements", measurementService.findAllOfThem(studyCaseNumber)) ;
return "study-case-detail" ;
}
The problem is that as the study cases listed in the first jsp could be thousands I will need to make it possible for the user to enter the study_case_number of a study case in a input field and get the details of the study case having the study case number inputed . So what I am doing is this:
<form action="<spring:url value="/studycase/study-case-detail2"/>" method="GET">
Study Case Number : <input type="text" name="studyCaseNumber">
<br/>
<input type="submit" value="Submit" />
</form>
That is being handled by an other controller and directs to an other jsp with more or less the same structure and data :
#RequestMapping("/studycase/study-case-detail2")
public String detail2(Model model, #RequestParam("studyCaseNumber") String std)
{
model.addAttribute("measurements", measurementService.findAllOfThem(std)) ;
return "study-case-detail2" ;
}
My question is this : Is this a good way to go having different controllers and different views even if they are presenting more or less the same thing ? What are other alternatives ??
Is there any source that you can direct me to containing best practices catalogue or guide on how to handle similar situations ??
Looking at your code, your controllers are not doing exactly the same thing (e.g. different model attributes, and they return different views).
Other than that, in general, it's not the best practice to do what you're doing as it somewhat in conflict with "Do Not Repeat Yourself" principle (also known as DRY principle).
One suggestion would be to use javascript to do redirect on id from input box rather than a form.
It seems you're using Spring Data too. If that's the case then one additional (not exactly related) suggestion to DRY up your code would be to use Spring Data's domain class converters to avoid calls studyCaseService.findOne(studyCaseNumber) in your StudyCase related controllers.
With domain class converters in place, you could then write controller method like this:
public String detail(Model model, #PathVariable("studyCaseNumber") StudyCase studyCase)
and avoid call to repository's findOne method as the converters would automatically convert ID to entity.
Take a look at DomainClassConverter in "Basic Web Support" section of Spring Data manual:
http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

JSTL c:set not working as expected

I have a JSTL loop where I'm trying to check to see if a given variable is empty or not with a dynamic variable name. When I use c:set with page scope, the variable is not accessible to the if statement. However, when I set it using <% pageCotnext.setAttribute(...); %>, the variable is available.
<%
pageContext.setAttribute("alphaParA", "test");
pageContext.setAttribute("alphaParF", "test");
int i = 0;
%>
<ul class="alphadex_links">
<c:forEach var="i" begin="0" end="25" step="1" varStatus="status">
<c:set var="currentLetter" scope="page">&#${i+65}</c:set>
<c:set var="currentPar" scope="page">alphaPar${currentLetter}</c:set>
<% pageContext.setAttribute("currentPar", "alphaPar" + (char)('A' + i++)); %>
<li>
<c:choose>
<c:when test="${not empty pageScope[currentPar]}">
The test is always fails when I remove the pageContext.setAttribute block, however it succeeds for A and F as it should when the block is in. I'm very confused and can't find help anywhere.
It fails because HTML doesn't run at the moment JSTL runs. You're effectively passing a Java String &#65 to it instead of the desired character A which would be represented as such based on the HTML entity A when the HTML is retrieved and parsed by the webbrowser after Java/JSP/JSTL has done its job. Please note that your HTML entity is missing the closing semicolon, but this isn't the cause of your concrete problem.
As to the concrete functional requirement, sorry, you're out of luck with EL. It doesn't support char. Your best bet is to deal with strings like this:
<c:forEach items="${fn:split('A,B,C,D,E,F,G,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z', ',')}" var="currentLetter">
<c:set var="currentPar" value="alphaPar${currentLetter}" />
${pageScope[currentPar]}
</c:forEach>
If necessary, just autogenerate the letters as String[] in Java end and set it as application attribute.

JSTL vs JSP Scriptlets

I want someone to explain some points in BlausC's amazing answer in this question.
He said that scriptlets had some disadvantages, which are:
Reusability: you can't reuse scriptlets. My question : how could I reuse JSTL code?
Replaceability: you can't make scriptlets abstract. What does abstract mean and how could JST become abstract?
OO: you can't make use of inheritance/composition. How could I use OO paradigms in JSTL?
Debugging: if a scriptlet throws an exception halfway, all you get is a blank page.
Testability: scriptlets can't be unit tested. What does that mean, and how can JSTL be unit tested?
Maintainability: per saldo, more time is needed to maintain mingled/cluttered/duplicated code logic. What does this mean?
The last thing is what he quoted form Oracle's recommendation:
JSP scriptlets should not be used for writing business logic.
In the MVC pattern, I use scriptlets only in the presentation layer. What does he mean here?
You seem to concentrate on only the presentation and flow-control part of the scriptlets as in using if, for and switch statements and out.print() things. You seem to compare scriptlets 1:1 with JSTL. This is wrong. I was not talking about the flow control part only (which is indeed to be replaced by JSTL), but about writing raw Java code in JSP files in general. I.e. gathering request parameters, validating and converting values, interacting with database and other Java classes/methods, etc. All things you normally (indirectly) do in a Servlet or Filter.
You should not have scriptlet code in JSPs. I'd recommend 100% JSTL and zero scriplet code.
JSPs should be purely presentation. That's the hidden benefit of writing JSPs using only JSTL, because they get all their dynamic data elsewhere. Let the service layer have the business logic and determine what data the JSP needs.
This answers your unit testing question, too. You should not have to unit test JSPs; those would be Selenium-like UI tests. If the logic is in the service tier, it's obvious how you test it.
JSPs should not be inherited. You can certainly compose them together using something like SiteMesh, but inheritance has no part in your JSPs. Once they inherit from Servlet, the chain should be ended.
Besides, it's a false alternative. Neither one should require reuse, inheritance, or unit testing. But that doesn't mean there isn't a clear winner: it's JSTL. No one should be using scriptlets in JSPs, except for very rare one-liners. Scriptlets are begging for trouble.
These days I prefer Velocity as my web UI template solution for Java, much more than JSPs. Just my opinion.
I can't speak for BalusC but in general I believe he was getting at the idea that these kinds of things should be accomplished by your ordinary Java code (in the Controller and Model layers if you're into the whole MVC thing).
You can't literally reuse JSP tags at an individual level, but you can reuse the classes they call into.
JSTL can't be abstract, but ordinary Java code (which you can perhaps invoke from JSTL) can be.
Again, you can't make objects usefully in jstl, but you can in all the classes that are called.
JSTL by itself is not unit-testable. But the classes and methods you call through it are.
It depends on the pattern you're using. By using the MVC (spring, struts, ...) you should avoid the usage of scriptlets in your JSP, because it represent the view it should contain pure XHTML tags. JSTL is a declarative language some kind of XML, while scriplet isn't.
Particularly I have used JSTL in combination with AJAX via prototype for generating RIA without needing to implement another pattern. Recently I have seen this kind of programming with ExtJS and DWR. In my case I found It was necessary to combine both JSTL and scriplets always preferring JSTL when possible.
<!-- simple controller, each action is called by means of AJAX -->
<% String signExt="jpg"; %>
<% int r=0, iMaxRows=0, iMaxCols=0;%>
<c:choose>
<c:when test="${param.action == 'get_chrequest_profile_table_by_family_and_date'}">
<sql:query var="dataset">
CALL GetProfilesView('<c:out value="${param.family_name}" />', '<c:out value="${param.reg_date}" />')
</sql:query>
<c:set var="strElements"><c:out value="${dataset.rowCount}" /></c:set>
<%
String strElements = pageContext.getAttribute("strElements").toString();
int iElements = (int)Integer.valueOf(strElements).intValue();
String to = "";
%>
<table class="tb_profiles" id="tb_profiles" iElements="<%=iElements%>"
width="100%" frame=void border="0" cellPadding="0" cellSpacing="0" style="border-top: 3px solid gray; border-left: 1px solid gray">
<%for(int i=1, j=0, col=0; i<100; i++){%>
<tr>
<%for(j=0; j<4; j++, col++){%>
<c:set var="c" scope="page"><%=col%></c:set>
<td name='<c:out value="${dataset.rows[c].chreqprofile_id}" />' >
<table width="100%" frame="below" cellPadding="0" cellSpacing="0"style="border-right: 1px solid gray;">
<%if( col < iElements){%>
<tr style="height:10mm">
<td class="td_function" style="cursor:default;">
<c:out value="${dataset.rows[c].description}" />
</td>
</tr>
.................
<tr style="height:14mm">
<td class="td_signature" align="center" vAlign="middle">
<img class="img_signature"
src='../xdata/signatures/<c:out value="${dataset.rows[c].responsible_name}"/>.<%=signExt%>'
alt='<c:out value="${dataset.rows[c].email}" />'
/>
</td>
</tr>
.................
<c:set var="sMail"><c:out value="${dataset.rows[c].email}"/></c:set>
<% if( col < iElements-1){
to = to + pageContext.getAttribute("sMail").toString() + ",";
}else{
to = to + pageContext.getAttribute("sMail").toString();
}
%>
<%}else{%>
<tr style="height:10mm">
<td class="td_function" style="cursor:default;">x</td>
.............
</tr>
<%}%>
</table>
</td>
<%}%>
</tr>
<%
if( col >= iElements){break;}
}%>
</table>
<span id="span_mail_to" style="display:none;"><%=to%></span>
</c:when>
<c:when test="${param.action == 'functions_form_insert'}">
.............
</c:when>
</c:choose>
I dont see that scriplets is too bad specially if you follows design pattern in it, I work a lot on spring mvc, in my jsp i just get the model data in scriplits, and i show it to the user using simple java code in html, i feel it give me more freedom than JSTL.
Here is a table comparing JSP and Facelets that may possibly be helpful to someone, somewhere:
Source

Converting an ArrayList<someObjects> to an HTML table

I have a couple of ArrayLists with variable length and sometimes null. This ArrayList contains a bunch of objects.
The table should have columns based on (some) attributes of the object. And the table should be displayed on a jsp.
I have two ideas, one is to use a JSTL tag the other is to use JavaScript. And library suggestions are welcome.
JSTL is the standard, preferred way (unless you need to load it via ajax, for example)
<table>
<tr><td>Foo header</td><td>Bar header</td></tr>
<c:forEach items="${yourRequestScopedArrayList}" var="obj">
<tr>
<td>${obj.foo}</td>
<td>${obj.bar}</td>
</tr>
</c:forEach>
</table>
JSTL is better,
Javascript you should avoid as much as possible ,
I am not sure how you are going to render datatable using java script and Collection
How to use jstl with collection that has been demonstrated by Bozho in the same thread.
Javascript doesn't have access to the Java objects that live (I presume) on the server. The server code can make the ArrayLists available to the JSP which can then loop over them with a JSTL forEach tag.
How you make the ArrayLists "available" depends on the framework you're using, but the plain servlet way is just setting an attribute from the doPost method.
request.setAttribute("list1", arrayList1);
The loop would be something like
<table>
<tr><th>Column 1</th> <th>Column 2</th> <th>Column 3</th></tr>
<c:forEach var="row" items="${list1}">
<tr><td>${row.col1data}</td> <td>${row.col2data}</td> <td>${row.col3data}</td></tr>
</c:forEach>
</table>

Categories