Is AntiSamy policy actual - java

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?

Related

A bit strange behaviour of Files.delete and Files.deleteIfExists

I got code like this:
paths.forEach(folderPath -> {
Path to = folderPath.getRoot().resolve(folderPath.getParent().subpath(0, folderPath.getNameCount() - 1)); // До имени (исключительно)
try {
Files.list(folderPath).forEach(filePath -> {
try { Files.move(filePath, to.resolve(filePath.getFileName()), StandardCopyOption.ATOMIC_MOVE); }
catch (IOException e) { processException(e); }
});
if (Files.list(folderPath).count() == 0)
Files.deleteIfExists(folderPath); // this call
} catch (IOException e) { processException(e); }
});
After I call delete methods, I get my empty directory locked (right after it was called, checked it), but not deleted until application is closed. I find it a bit strange, but want to know why is this happening.
(I use Windows 10)
From the documentation of Files.list(Path):
This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directory is closed promptly after the stream's operations have completed.
You are not doing this, so the following part of Files.deleteIfExists(…) applies:
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
You should use
paths.forEach(folderPath -> {
Path to = folderPath.getParent();
try {
try(Stream<Path> files = Files.list(folderPath)) {
files.forEach(filePath -> {
try{Files.move(filePath, to.resolve(filePath.getFileName()), ATOMIC_MOVE);}
catch (IOException e) { processException(e); }
});
}
try {
Files.deleteIfExists(folderPath);
} catch(DirectoryNotEmptyException ex) {
// may happen as you continue when Files.move fails,
// but you already reported the original exception then
}
} catch (IOException e) { processException(e); }
});
This closes the stream of files before trying to delete the directory. Note that the second stream operation has been removed, this kind of pre-check is wasteful and should be unneeded when all move operations succeeded. But if some other application inserts a new file concurrently, there is no guaranty that it doesn’t happen between your Files.list(folderPath).count() == 0 check and the subsequent deleteIfExists call.
The cleaner solution would be to remember when a move failed. When no move failed, a still not empty directory should be considered an erroneous situation that should be reported like any other error, e.g.
paths.forEach(folderPath -> {
Path to = folderPath.getParent();
try {
boolean allMovesSucceeded;
try(Stream<Path> files = Files.list(folderPath)) {
allMovesSucceeded = files
.map(filePath -> {
try {
Files.move(filePath, to.resolve(filePath.getFileName()), ATOMIC_MOVE);
return true;
}
catch(IOException e) { processException(e); return false; }
}).reduce(Boolean.TRUE, Boolean::logicalAnd);
}
if(allMovesSucceeded) Files.deleteIfExists(folderPath);
} catch (IOException e) { processException(e); }
});

AntiSamy to prevent XSS in java?

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

Liferay 7 Error when trying to get web content inside portlet

i am trying to use JournalArticleServiceUtil class to get web content, but it shows an error and i don't know how to fix it, there's my code
long groupId = themeDisplay.getLayout().getGroupId();
System.out.println("GroupId: " + groupId);
List<JournalArticle> articleList = new ArrayList<>();
List<String> news = new ArrayList<>();
try {
DDMStructure structure = DDMStructureManagerUtil.getStructure(Long.parseLong("94203"));
articleList = JournalArticleServiceUtil.getArticlesByStructureId(groupId, structure.getStructureKey(), 0, 10, null);
for (JournalArticle art: articleList) {
news.add(art.getContent());
}
} catch (SystemException e) {
log.error(e.getMessage());
} catch (NumberFormatException e) {
log.error(e.getMessage());
} catch (PortalException e) {
log.error(e.getMessage());
}
the error says
com.sun.proxy.$Proxy466 cannot be cast to com.liferay.journal.service.JournalArticleService
i hope you can help me with this
This seems related to the implementation version of the service class you are using. If you are using gradle, you could give preference to compileOnly rules and make sure you match the kernel version in you server with the one you are using. Some times you do need to declare implementation versions directly on you bnd.bnd.
Something like:
Import-Package: com.liferay.journal.model;version="[1.0.0,3.0.0)", com.liferay.journal.service; version="[1.0.0,3.0.0)",*
I think you should try using JournalArticleLocalServiceUtil instead of JournalArticleServiceUtil.

Accessing web API protected by Azure AD using a web app client

Can someone please explain me how to access the protected web api using a web app client?
I am trying something mentioned here in the following link. But I am always getting
The provided access grant is invalid or malformed.
https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
Here is the code i am using for java
AuthenticationResult result = null;
try {
final Future<AuthenticationResult> resultFuture = context.acquireTokenByAuthorizationCode(
code, new URI(redirectUri), new ClientCredential(clientId, clientSecret), RESOURCE_GRAPH_API, null);
result = resultFuture.get();
} catch (InterruptedException | ExecutionException e) {
LOG.info("Failed to obtain access token: " + e.getMessage());
} catch (URISyntaxException e) {
}

Not possible to launch a file on a network using Java Desktop?

(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)

Categories

Resources