Can Fortify identify the servlet filter? - xss

I used the filter to fix the XSS. But when i scan my codes using fortify software, the number of XSS issues didn't change. Did i miss something? or Fortify cannot recognize the filter? Here are my filter codes:
public final class RequestWrapper extends HttpServletRequestWrapper {
public RequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values==null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
return cleanXSS(value);
}
public String getHeader(String name) {
String value = super.getHeader(name);
if (value == null)
return null;
return cleanXSS(value);
}
private String cleanXSS(String value) {
System.out.println("filter : " + value);
//System.out.println("afterfilter : " + (isNotEmptyOrNull(value) ? StringEscapeUtils.escapeHtml4(value) : value));
//return isNotEmptyOrNull(value) ? StringEscapeUtils.escapeHtml4(value) : value;
if(isNotEmptyOrNull(value)){
value = value.replaceAll("<", "<").replaceAll(">", ">");
value = value.replaceAll("\\(", "(").replaceAll("\\)", ")");
value = value.replaceAll("'", "'");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
}
System.out.println("afterfilter : " +value);
return value;
}
public static boolean isNotEmptyOrNull(String string) {
if (string != null && !"".equals(string.trim())) {
return true;
}
return false;
}
}

The problem here is that Fortify doesn't have a rule for your cleanXSS method. What you will have to do is to write a custom rule, specifically a "data flow cleanse rule". This will let fortify know that any data that enters and then returned from this method will be safe from XSS.
However after looking at you XSS filter, I have to inform you that it's incomplete and will not take in to account all possible XSS vectors. I recommend that you use OWASP ESAPI's XSS filter. Fortify already has a rules for ESAPI.

Related

Working with Inner List containing Item with specific Property value, Java 8

I created a code, for specific task. But, I think: must to have better manner to do this code.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class InnerListContainingItemWithSpecificPropertyValue {
public static void main(String[] args) {
List<List<Person>> nestedPersonList = Arrays.asList(
Arrays.asList(new Person("a0", 0), new Person("b0", 1)), //0
Arrays.asList(new Person("a1", 0), new Person("b1", 1)), //1
Arrays.asList(new Person("a2", 0), new Person("b2", 1)), //2
Arrays.asList(new Person("a3", 0), new Person("b3", 1)) // 5
);
List<List<Person>> outNestedPersonList = new ArrayList<>();
nestedPersonList.stream().flatMap(List::stream).forEach(outerPerson -> {
//Determine if Exist Some inner List
boolean ageFound = outNestedPersonList
.stream()
.flatMap(List::stream)
.filter(innerPerson -> outerPerson.getAge() == innerPerson.getAge())
.count() > 0L;
List<Person> listPersonWithAge;
if (!ageFound) {
listPersonWithAge = new ArrayList<>();
outNestedPersonList.add(listPersonWithAge);
} else {
// Get the Inner List with Specific Property Value
listPersonWithAge = outNestedPersonList
.stream()
.filter(innerListPerson -> {
return innerListPerson
.stream()
.filter(innerPerson -> outerPerson.getAge() == innerPerson.getAge())
.count() > 0L;
}).findFirst().get();
}
listPersonWithAge.add(outerPerson);
// Do something
if (listPersonWithAge.size() == 4) {
System.out.println("listPerson with age:" + outerPerson.getAge() + "\twill be removed!");
outNestedPersonList.remove(listPersonWithAge);
}
});
}
public static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public int hashCode() {
int hash = 5;
hash = 73 * hash + Objects.hashCode(this.name);
hash = 73 * hash + this.age;
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (this.age != other.age) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Person{" + "name=" + name + ", age=" + age + '}';
}
}
}
output:
listPerson with age:0 will be removed!
listPerson with age:1 will be removed!
Alternatively my code:
How know if is there inner List containing some item with some
Property Value?
How I can to obtain the inner list with that item?
If the external list does not contain an internal list, How create one?
The first step of improving your code is to avoid using flatMap. It makes it easier to operate on the nested data, but you are trying to operate on one of the sublists, not on the all of the people as a whole.
You are trying to operate on one sublist, not all of the people in all of the lists, so instead of using flatMap, you can nest two sets of stream operations.
listOfListOfPeople.stream()
// filter out sublists that don't have anyone with the target age
.filter(sublist ->
// Check if the nested list contains anyone with the given age
sublist.stream().anyMatch(p -> p.age == targetAge))
// get one sublist out of the stream
.findAny()
// if there wasn't one, get an empty list
.orElse(Collections.emptyList());
If you want to be able to modify the empty list you get if there aren't any people with the target age, replace the last line with something like .orElseGet(ArrayList::new).

MP3 Tagging ID3v2_3 Id3v2_4

I use the JID3 library which works fine for IDv2_3 but when it is asked to update a tracks tags which are V2_4, it simply wipes the Id3v2_4 tags. How can I test which version of tagging a track has.
Example of setting the ratings and times played in the POPULARIMETER tag
public String setmp3RatingTag(Context context, File SourceFile, String email, int rating, int timesPlayed) throws Exception {
String error = null;
if (timesPlayed < 0) {
timesPlayed = 0;
}
try {
MediaFile MediaFile = new MP3File(SourceFile);
ID3V2_3_0Tag ID3V2_3_0Tag = (org.blinkenlights.jid3.v2.ID3V2_3_0Tag) MediaFile.getID3V2Tag();
POPMID3V2Frame popmid3V2Frame = new POPMID3V2Frame(email, rating, timesPlayed);
popmid3V2Frame.setPopularity(email, rating, timesPlayed);
if (ID3V2_3_0Tag != null) {
frames = ID3V2_3_0Tag.getPOPMFrames();
if (frames != null) {
if (frames.length > 0) {
String emailtouser[]=getmp3Email(SourceFile);
for (int i = 0; i < frames.length; i++) {
if (frames[i] != null) {
ID3V2_3_0Tag.removePOPMFrame(emailtouser[i]);
}
}
}
}
} else {
ID3V2_3_0Tag = new ID3V2_3_0Tag();
}
ID3V2_3_0Tag.addPOPMFrame(popmid3V2Frame);
MediaFile.setID3Tag(ID3V2_3_0Tag);
MediaFile.sync();
} catch (ID3Exception | OutOfMemoryError e) {
e.printStackTrace();
error = e.getMessage();
}
error = finish(context, SourceFile);
return error;
}
For anyone using the jid3 library, I added another method to the class MP3File.java
#Override
public int testforVerion() {
int iMinorVersion=0;
try {
InputStream oSourceIS = new BufferedInputStream(m_oFileSource.getInputStream());
ID3DataInputStream oID3DIS = new ID3DataInputStream(oSourceIS);
try
{
// check if v2 tag is present
byte[] abyCheckTag = new byte[3];
oID3DIS.readFully(abyCheckTag);
if ((abyCheckTag[0] == 'I') && (abyCheckTag[1] == 'D') && (abyCheckTag[2] == '3'))
{
// check which version of v2 tags we have
iMinorVersion = oID3DIS.readUnsignedByte();
}
else
{
return iMinorVersion;
}
}
finally
{
oID3DIS.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return iMinorVersion;
}
simply check for value 3 for ID3V2_3 and 4 for ID3V2_4

Unity Iterate over a list to sort by the number value

I have a text file called highscore.txt and I know the format of the data going into the file which works in the following way:
Username:score
I then need to search through the whole file to see where the new score needs to be added such that the file is in order of score from largest to smallest
List<string> tempoaryList = new List<string>();
List<int> valueList = new List<int>();
string lineValues = "";
using (StreamReader sr = new StreamReader(finalPath))
{
while (sr.EndOfStream == false)
{
lineValues = sr.ReadLine();
tempoaryList.Add(lineValues);
int data = Convert.ToInt32(lineValues.Substring(lineValues.LastIndexOf(':') + 1));
valueList.Add(data);
}
}
valueList.Sort();
for(int i =0; i > valueList.Count; i++)
{
if(valueList[i] <= playerScore)
{
tempoaryList.Insert(i - 1, playerScore.ToString());
}
}
using (StreamWriter sw = new StreamWriter(finalPath, false))
{
for (int i = 0; i < tempoaryList.Count; i++)
{
sw.WriteLine(tempoaryList[i]);
Debug.Log(tempoaryList[i]);
}
}
The above just simply doesn't change the text file and leaves it as it was found, any ideas of what I am doing wrong?
You should change your code to this:
ScoreList.cs
using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
public class ScoreList : MonoBehaviour {
private void Start() {
GameOver.GameOverEvent += UpdateScoreBoardFile;
}
private void UpdateScoreBoardFile(string playerName, int playerScore) {
string lineValues;
string finalPath = "[ScoreBoard File Location]";
List<string> tempoaryList = new List<string>();
List<int> valueList = new List<int>();
bool isScoreLowest = true;
using (StreamReader sr = new StreamReader(finalPath)) {
while (sr.EndOfStream == false) {
lineValues = sr.ReadLine();
tempoaryList.Add(lineValues);
int data = Convert.ToInt32(lineValues.Substring(lineValues.LastIndexOf(':') + 1));
valueList.Add(data);
}
}
if (tempoaryList != null) {
for (int i = 0; i < valueList.Count; i++) {
if (valueList[i] <= playerScore) {
tempoaryList.Insert(i, playerName + ":" + playerScore.ToString());
isScoreLowest = false;
break;
}
}
}
if (isScoreLowest) {
tempoaryList.Add(playerName + ":" + playerScore.ToString());
}
using (StreamWriter sw = new StreamWriter(finalPath, false)) {
for (int i = 0; i < tempoaryList.Count; i++) {
sw.WriteLine(tempoaryList[i]);
Debug.Log(tempoaryList[i]);
}
}
}
}
GameOver.cs (or wherever you manage the game over condition):
using UnityEngine;
using System;
public class GameOver : MonoBehaviour {
public static event Action<string, int> GameOverEvent;
string playerName;
int finalScore;
private void GameOver() {
//Do other stuff when the game is over
GameOverEvent(playerName, finalScore);
}
}
Explanation of the changes:
isScoreLowest is needed to Add the new lowest score at the end of the list, since the for loop won't add it by itself.
The if (tempoaryList != null) check is done to skip the for loop when the scoreboard is empty.
And you saved yourself from doing a Sort, which is always a good thing. :)

How to bind ComboBox to a list in JavaFX?

My application periodically adds Strings to a List using a Thread. I want to add those strings to a ComboBox as soon as they get added to the List. Is there anyway to bind a ComboBox to a List?
My Code:
static final int max = 20;
List<String> ips = new ArrayList<String>();
public void getIP() throws UnknownHostException {
Task task = new Task<Void>() {
#Override
public Void call() throws UnknownHostException {
InetAddress localhost = InetAddress.getLocalHost();
byte[] ip = localhost.getAddress();
for (int i = 10; i <= max; i++) {
if (isCancelled()) {
break;
}
try {
ip[3] = (byte) i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(100)) {
//============================== Populating List ===============//
ips.add(address.getHostName());
}
} catch (Exception e) {
System.err.println(e);
}
updateProgress(i, max);
}
return null;
}
};
//============================== Bind ComboBox to List Code here ===============//
indicator.progressProperty().bind(task.progressProperty());
new Thread(task).start();
}
No there is no way to bind a simple list, since it's not observable. Even with a ObservableList, there would be the problem of the updates coming from a different thread.
You could however use a synchronized list and use the value property to pass the current size, which would allow you to add the items via listener.
Example
This uses a ListView instead of a ComboBox, since the results are visible without user interaction, but you could also use targetList = comboBox.getItems().
#Override
public void start(Stage primaryStage) {
ListView<String> listView = new ListView<>();
List<String> targetList = listView.getItems();
final List<String> ips = Collections.synchronizedList(new ArrayList<>());
Task<Integer> task = new Task<Integer>() {
#Override
protected Integer call() throws Exception {
Random random = new Random();
int size;
for (size = 0; size < 100; size++) {
ips.add(Integer.toString(size));
updateValue(size);
Thread.sleep(random.nextInt(500));
}
return size;
}
};
task.valueProperty().addListener((observable, oldValue, newValue) -> {
// add values not yet in the target list.
for (int i = targetList.size(), newSize = newValue; i < newSize; i++) {
targetList.add(ips.get(i));
}
});
new Thread(task).start();
Scene scene = new Scene(listView);
primaryStage.setScene(scene);
primaryStage.show();
}
It would be a bit simpler though to simply post the updates on the ui thread using Platform.runLater though:
ips = comboBox.getItems();
Task task = new Task<Void>() {
#Override
public Void call() throws UnknownHostException {
InetAddress localhost = InetAddress.getLocalHost();
byte[] ip = localhost.getAddress();
for (int i = 10; i <= max; i++) {
if (isCancelled()) {
break;
}
try {
ip[3] = (byte) i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(100)) {
//============================== Populating List ===============//
final String hostName = address.getHostName();
// do update on application thread
Platform.runLater(() -> ips.add(hostName));
}
} catch (Exception e) {
System.err.println(e);
}
updateProgress(i, max);
}
return null;
}
};
i suggest you to do the following:
change
List<String> ips = new ArrayList<String>();
to
final ObservableList<String> ips = FXCollections.observableArrayList();
change:
Task task = new Task<Void>()
to
Task<ObservableList<String> task = new Task<>(){
#Override
public ObservableList<String> call() throws UnknownHostException {
...
return ips;
}
};
comboBox.itemsProperty().bind(task.valueProperty());

Error : a 'for each' statement cannot operate on an expression of type "MyKinect::ActionKeys []"

I'm very new to c# and c++. I want to convert C# code into C++ but I have an error on for each (auto key in keys). Would you mind telling me what I am doing wrong. Many thanks.
C# code :
Public InputResule GetKey(ActionKeys[] keys)
{
InputResule ir = new InputResule();
foreach (var key in keys)
{
var data = mActionList.FirstOrDefault(p => p.Key == key);
if (data.Value != MovementType.None)
{
ir = CheckMovement(data.Value);
}
}
return ir;
}
C++ Code :
InputResule KinectInput::GetKey(ActionKeys keys[])
{
InputResule ir = InputResule();
for each (auto key in keys)
{
auto data = mActionList.find(key->first);
{
return p->Key == key;
};
if (data->Value != MovementType::None)
{
ir = CheckMovement(data->Value);
}
}
return ir;
}