Basically I have a web-app which it currently is vulnerable to XSS. Based on my research I found one of good and open library that can help would be AntiSamy. So I downloaded the library .jar file which is antisamy-1.5.1.jar and The policy file antisamy-slashdot-1.4.4.xml and exported it to my project WEB-INF directory.
I'm pretty much new to AntiSamy and don't really know how to implement it on a string to encode and secure it from XSS.
Say I've a string of: String XSSPossible = "<script>alert("It's vulnerable.");</script>"; Now I want to encode this to a normal text and secure it from XSS.
Much Regards.
You can use below code
public class AntisamySample
{
public static AntiSamy antiSamy;
public static Policy policy;
public static CleanResults cleanResults;
static String policyFileName = "antisamy-slashdot-1.4.4.xml";
private Policy gtePolicyFile()
{
try
{
policy = policy.getInstance(this.getClass().getResourceAsStream(policyFileName));
}
catch (PolicyException e)
{
e.printStackTrace();
}
return policy;
}
public static void main(String[] args)
{
String XSSPossible = "<script>alert('It's vulnerable.');</script>";
String cleanResult = "";
try
{
AntisamySample antisamy = new AntisamySample();
antiSamy = new AntiSamy();
policy = antisamy.gtePolicyFile();
cleanResults = antiSamy.scan(XSSPossible, policy);
cleanResult = cleanResults.getCleanHTML();
}
catch(PolicyException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ScanException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This will return you clean HTML
All the rules to get clean HTML are in antisamy*.xml file. There are four different policy files.
As per your requirements you can use any policy file and add rules as per your requirements.
Here is the more details about antisamy
Related
I am trying to write something to a ini file using ini4j.
When i call the store() method it throws a FileNotFound exception even though it is in my project directory.
Maybe i did something wrong with my code?
Main:
public class Main {
public static Wini ini = null;
public static void main(String[] args) {
Config conf = new Config();
try {
conf.setMultiOption(true);
ini = new Wini();
ini.setConfig(conf);
ini.load(new File("apikeys.ini"));
} catch (InvalidFileFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The file where i attempt to write and store the data:
if (KeyEndpoint.isValid(apikey)) {
Main.ini.put(apikey, Main.ini.get("Apikey"));
try {
Main.ini.store();
} catch (IOException e) {
channel.sendMessage("Invalid api key.").queue();
}
} else {
channel.sendMessage("API Key is invalid.").queue();
}
Any help is appreciated, I at least want to know what I am doing wrong.
Thanks!
It has to do with relative paths. Try changing the filename in Main for the absolute path, something like "/tmp/apikeys.ini", to check that your code works correctly. If that works, then you can now change it to either something like "../../directory/filename" or something relative to where you know you're executing your code from. Get familiar with your java path environment variables such as JAVA_HOME and all to get it to something more permanent and portable.
I use the following code to filter out javascript code in user-submitted html files on Android:
Policy antiSamyPolicy;
try {
antiSamyPolicy = Policy.getInstance(AntiSamy.class.getResourceAsStream("/antisamy.xml"));
} catch (PolicyException e) {
e.printStackTrace();
return;
}
AntiSamy antiSamy = new AntiSamy(antiSamyPolicy);
CleanResults result;
try {
result = antiSamy.scan(taintedHtml);
} catch (PolicyException | ScanException e) {
e.printStackTrace();
return;
}
It loads bundled policy "antisamy.xml" which is included in AntiSamy (https://github.com/nahsra/antisamy).
All seems to work ok. The only question is how actual is the policy? Is it enough to filter out all javascript code in contemporary html?
I'm a newbie programmer looking for a way to implement a simple file transfer protocol on Android.
Problem:
Several Android phones need to connect to a server to receive/send a series of XML files saved in internal storage. The server needs to know which phone is requesting a connection so that it can save the files in the correct folder.
Possible solution/algorithm:
There are various tutorials/examples on how to send a file to a server, but none of them seem to implement some kind of "authentication".
Ideally I would like to implement the following (I'll use a metaphor):
Phone: Hello.
Server: Hi. Who are you and what do you want? [send/receive]
Phone A: I'm phone A and I would like to send files.
Server: How many files do you want to send, Phone A?
Phone A: 6 files, [+extra data like total size or whatever]
Server: Alright, you can begin the transfer.
Phone A: Transfers...
Server: I've succesfully received 6 files, have a good day. [stores the files in a PhoneA folder]
Phone A: Bye! [closes connection]
I realise this could very likely be made a lot more efficient, but I don't know where to begin...
Is it even possible to initiate a connection with a server and interact multiple times while waiting for responses?
Question :
Could anyone push me in the right direction somehow? Do I write my own protocol or can this be done with standard functionality? What are the best/easiest existing protocols for this kind of implementation?
I've found this article interesting but I don't see how it could be used for multiple files with authentication
Any help would be much appreciated!
This is easier than you think using old-school FTP, which I've used with success in collecting data from apps, and your server will surely support it.
Get a unique ID for each Android device using enter link description here. You get a 64-bit number (as a hex string) that is randomly generated on each device’s first boot. It's supposedly constant for the life of the device.
Import Apache Commons FTP and use the method describe here to create a directory name inside your working directory on the server with a name matching the unique id.
Use the same library to upload the files using FTP. You'll find many example of how to do this. It takes very minimal code.
Unlike your chat scenario, this is a very client-side solution, and phones you might not want to could upload files -- there's no blacklist -- but it's easy to implement.
For those interested in (terrible) code to perform various FTP functions, here's what worked for me.
It requires the apache commons ftp jar file which can be found on the internet.
//Button that starts it all
public void updateWorkordersList(View view) {
if (!CheckNetworkConnection.isOnline()) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String connectionString = prefs
.getString("connection_string", null);
String userName = prefs.getString("FTPusername", null);
DownloadFilesTask task = new DownloadFilesTask(connectionString,
userName);
task.execute();
Fragment frg = null;
frg = getFragmentManager()
.findFragmentByTag("buttonsContainer");
final FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Boolean> {
private FTPClient mFtpClient = new FTPClient();
private FTPFile[] mFileArray;
private String _address;
private String _user;
private String _pass;
public DownloadFilesTask(String ip, String user) {
_address = ip;
_user = user;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
mFtpClient.setConnectTimeout(10 * 1000);
mFtpClient.connect(InetAddress.getByName("insert server here"));
boolean status = mFtpClient.login("username", "password");
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
mFtpClient.setFileType(FTP.ASCII_FILE_TYPE);
mFtpClient.enterLocalPassiveMode();
mFileArray = mFtpClient.listFiles();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Download All Files
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
File directory = null;
directory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath());
for (FTPFile file : mFileArray) {
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(
new FileOutputStream(directory + "/"
+ file.getName()));
mFtpClient.setFileType(FTP.BINARY_FILE_TYPE);
mFtpClient.retrieveFile(file.getName(), outputStream);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//Upload All Files
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
File directory = null;
directory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath() + "/srvReady");
for (File file : directory.listFiles()) {
try {
FileInputStream srcFileStream = new FileInputStream(directory + "/" + file.getName());
boolean status = mFtpClient.storeFile(_user + "/" + file.getName(),
srcFileStream);
srcFileStream.close();
if (status){
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try {
mFtpClient.logout();
mFtpClient.disconnect();
} catch (Exception e) {
// TODO: handle exception
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
}
}
I figure this could be of some use might someone ever come across a similar problem.
I want to run an action (with a rule) when a file enters the folder in my alfresco repository. The file needs to be moved to a new folder. The new folder will be named after the metadata property "subject" from the file I uploaded.
I am not able to figure out how to do this. Who got any tips?
(A repository webscript is also an option).
This is how I see it:
import java.util.List;
public class MoveExecuter extends ActionExecuterAbstractBase {
public static final String DESTINATION_FOLDER = "destination-folder";
private FileFolderService fileFolderService;
private NodeService nodeService;
#Override
protected void addParameterDefinitions(List<ParameterDefinition> paramList) {
paramList.add(
new ParameterDefinitionImpl(DESTINATION_FOLDER,
DataTypeDefinition.NODE_REF,
true,
getParamDisplayLabel(METADATA VALUE FROM FIELD SUBJECT FROM INCOMING FILE)));}
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
NodeRef destinationParent = (NodeRef)ruleAction.getParameterValue(DESTINATION_FOLDER);
// if the node exists
if (this.nodeService.exists(destinationParent) == true) {
try {
fileFolderService.move(incomingfile, destinationParent, null);
} catch (FileNotFoundException e) {
// Do nothing
}
if (this.nodeService.exists(destinationParent) == false) {
try {
nodeService.createNode(parentRef, assocTypeQName, assocQName, "metadata field subject");
fileFolderService.move(incomingfile, destinationParent, null);
} catch (FileNotFoundException e) {
// Do nothing
}
}
}
}
For such a simple action I'd just use a JavaScript instead of a java Action.
Install the JavaScript addon from googlecode or github (newer version)
And just write your Javascript code according the api and run it in runtime in the console to test your code.
(I have a problem that I illustrated in this question but had no correct answers. I refined my problem and tried to edit the initial question to reflect that but I guess because of the way SO displays unanswered questions it lost momentum and there is no way to revive it. So I am posting my correct question again).
I have a file that resides on a shared network location :
"\\KUROSAVVAS-PC\Users\kuroSAVVAS\Desktop\New Folder\Warsaw Panorama.JPG"
(The spaces are there intentionally)
The following code :
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
String s = "\\\\KUROSAVVAS-PC\\Users\\kuroSAVVAS\\Desktop\\New Folder\\Warsaw Panorama.jpg";
File f = new File(s);
System.out.println(f.exists());
Desktop.getDesktop().open(f);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Prints to the console that the file exists (System.out.println(f.exists());) but throws this exception! :
java.io.IOException: Failed to open file:////KUROSAVVAS-PC/Users/kuroSAVVAS/Desktop/New%20%20%20%20%20Folder/Warsaw%20%20%20%20Panorama.jpg. Error message: The system cannot find the file specified.
at sun.awt.windows.WDesktopPeer.ShellExecute(WDesktopPeer.java:59)
at sun.awt.windows.WDesktopPeer.open(WDesktopPeer.java:36)
at java.awt.Desktop.open(Desktop.java:254)
at Test.main(Test.java:13)
Has anyone any idea why something like this may happen? I have tried everything from creating URIs to decoding them afterwards... Nothing works.
With java 7 you can do this
public static void main(String[] args) throws IOException {
String s = "\\\\KUROSAVVAS-PC\\Users\\kuroSAVVAS\\Desktop\\New Folder\\Warsaw Panorama.jpg";
Path p = Paths.get(s);
Desktop.getDesktop().browse(p.toUri());
}
Java 6 solution:
public static void launchFile(File file) {
if (!Desktop.isDesktopSupported())
return;
Desktop dt = Desktop.getDesktop();
try {
dt.open(file);
} catch (IOException ex) {
// this is sometimes necessary with files on other servers ie
// \\xxx\xxx.xls
launchFile(file.getPath());
}
}
// this can launch both local and remote files
public static void launchFile(String filePath) {
if (filePath == null || filePath.trim().length() == 0)
return;
if (!Desktop.isDesktopSupported())
return;
Desktop dt = Desktop.getDesktop();
try {
dt.browse(getFileURI(filePath));
} catch (Exception ex) {
ex.printStackTrace();
}
}
// generate uri according to the filePath
private static URI getFileURI(String filePath) {
URI uri = null;
filePath = filePath.trim();
if (filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0) {
if (filePath.indexOf("\\") == 0){
filePath = "file:" + filePath;
filePath = filePath.replaceAll("#", "%23");
}
try {
filePath = filePath.replaceAll(" ", "%20");
URL url = new URL(filePath);
uri = url.toURI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
} else {
File file = new File(filePath);
uri = file.toURI();
}
return uri;
}
This answer was on the bug report, but I've edited it to fix when there is a hash.
TL;DR of ZAMMBI's answer (+1 BTW). (Using Java 6)
This works, as expected
Desktop.getDesktop().open(new File("\\\\host\\path_without\\spaces.txt")); //works
This fails, due to a known Java bug:
Desktop.getDesktop().open(new File("\\\\host\\path with\\spaces.txt")); //fails <shakes fist>
This work-around works
Desktop.getDesktop().browse(new URI("file://host/path%20with/spaces.txt")) //works (note slash direction and escape sequences)
This work-around seems like it should work, but does not:
Desktop.getDesktop().browse((new File("\\\\host\\path with\\spaces.txt")).toURI());
This work-around works, and seems to be the most general form:
File curFile = new File("\\\\host\\path with\\or_without\\spaces\\local or network.txt");
Desktop.getDesktop().browse(new URI(curFile .toURI().toString().replace("file:////","file://")));
It seems that there is a bug when you try to access a resource on a network drive with spaces in the path. See this entry in Sun's bug database.
Since the bug is already a year old, I don't think you'll get a fix anytime soon. Try the latest VM. If that doesn't help, try to get the source for WDesktopPeer. Instead of encoding the path, try to keep it as it was (with backslashes and all) and put quotes around it. That might work.
[EDIT] Specifically, don't replace \ with /, do not prepend file:// and leave the spaces as they are (instead of replacing them with %20)