Protection against Cross site scripting on specific JSP and Servlet code - xss

Here are the servelet cum JSP code, let me know how we could protect them from XSS?
Servlet Code:
String strRequestScrip = SecurityCheck.getStringParameter(request,PARAM_SCRIP_CODE);
List arrScripLocator = MarketWatchUtils.getEqScripLocator(strRequestScrip, strExchangeCode, application);
request.setAttribute("arrScripLocator", arrScripLocator);
request.getRequestDispatcher("/ajax/ajaxScripLocator.jsp").forward(request, response);
Jsp Code:
final List arrScripLocator = (List) request.getAttribute("arrScripLocator");
int intScripLocatorSize = arrScripLocator != null ? arrScripLocator.size() : 0;
intScripLocatorSize = intScripLocatorSize <= 20 ? intScripLocatorSize : 20;
out.print(intScripLocatorSize);

You should use Jsoup to sanitize the request.
The code will look like this:
String unsafe ="<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>";
String safe = Jsoup.clean(unsafe, Whitelist.basic());
// now: <p>Link</p>
I recommend you also read the OWASP XSS Filter Evasion Sheet.

Related

Get Returned text from ScriptManager(javascript) - INDESIGN SDK Plugin

I am using javascript inside my Plugin for Indesign CS6.
It is working fine.
But I need the return value from my javascript code now inside my c++ code.
I am using this site as reference:
https://blogs.adobe.com/indesignsdk/running-a-script-from-an-indesign- plug-in/
I need something like that:
scriptRunner->RunScript("function xpto(){return 'Hello World';};xpto()", params);
// fake method
const char *string_return = scriptRunner->getReturnCode();
are there something like that on scriptManager?
ps: it is not a indesign server. I put this tag because this site do not let me create a new tag...
Best Regards,
Use RunScriptParams::QueryScriptRequestData() .
From the SDK documents:
Query the IScriptRequestData that is used to pass arguments and return
the result.
The key is to get the iScript object from the 'RunScriptParams' object after the script has run. Then is it straight forward. Here is some sample code:
RunScriptParams params(scriptRunner);
IScriptRequestData* requestData = params.QueryScriptRequestData();
params.SetUndoMode(RunScriptParams::kFastUndoEntireScript);
if (scriptRunner->RunScript(script,params) != kSuccess) return NULL;
IScript *iScript = params.QueryTarget();
int resultsCount = requestData->GetNumReturnData(iScript);
PMString resultString;
if (resultsCount > 0) {
ScriptReturnData resultOne = requestData->GetNthReturnData(iScript,0);
ScriptData scriptReturnOne = resultOne.GetReturnValue();
scriptReturnOne.GetPMString(resultString);
}
The return value is in resultString.

How to specify language, location and city with facebook graph api

I am using FacebookGraphAPIDesktop.swc api to create unpublished post.
How can I assign language, location and city parameter with it?
Currently I am creating it like below :-
var params:Object = new Object();
params.access_token = PhotoToken;
params.published = 0;
params.message = "Test unpublished post";
FacebookDesktop.api("/" + PageID +"/feed", StatusPosted, params,"POST");
thanks in advance
I found the solution and posting here if anyone needs it :-
We need to pass it as a json string :-
var targeting:String = "{'countries':['US','IN']}";
_params.access_token = token;
_params.published = 0;
_params.message = "This is status message 5";
_params.targeting = targeting;
FacebookDesktop.api("/202387076493582/feed", messagePosted1, _params,"POST");

How do I query multiple IDs via the ContentSearchManager?

When I have an array of Sitecore IDs, for example TargetIDs from a MultilistField, how can I query the ContentSearchManager to return all the SearchResultItem objects?
I have tried the following which gives an "Only constant arguments is supported." error.
using (var s = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
rpt.DataSource = s.GetQueryable<SearchResultItem>().Where(x => f.TargetIDs.Contains(x.ItemId));
rpt.DataBind();
}
I suppose I could build up the Linq query manually with multiple OR queries. Is there a way I can use Sitecore.ContentSearch.Utilities.LinqHelper to build the query for me?
Assuming I got this technique to work, is it worth using it for only, say, 10 items? I'm just starting my first Sitecore 7 project and I have it in mind that I want to use the index as much as possible.
Finally, does the Page Editor support editing fields somehow with a SearchResultItem as the source?
Update 1
I wrote this function which utilises the predicate builder as dunston suggests. I don't know yet if this is actually worth using (instead of Items).
public static List<T> GetSearchResultItemsByIDs<T>(ID[] ids, bool mustHaveUrl = true)
where T : Sitecore.ContentSearch.SearchTypes.SearchResultItem, new()
{
Assert.IsNotNull(ids, "ids");
if (!ids.Any())
{
return new List<T>();
}
using (var s = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
var predicate = PredicateBuilder.True<T>();
predicate = ids.Aggregate(predicate, (current, id) => current.Or(p => p.ItemId == id));
var results = s.GetQueryable<T>().Where(predicate).ToDictionary(x => x.ItemId);
var query = from id in ids
let item = results.ContainsKey(id) ? results[id] : null
where item != null && (!mustHaveUrl || item.Url != null)
select item;
return query.ToList();
}
}
It forces the results to be in the same order as supplied in the IDs array, which in my case is important. (If anybody knows a better way of doing this, would love to know).
It also, by default, ensures that the Item has a URL.
My main code then becomes:
var f = (Sitecore.Data.Fields.MultilistField) rootItem.Fields["Main navigation links"];
rpt.DataSource = ContentSearchHelper.GetSearchResultItemsByIDs<SearchResultItem>(f.TargetIDs);
rpt.DataBind();
I'm still curious how the Page Editor copes with SearchResultItem or POCOs in general (my second question), am going to continue researching that now.
Thanks for reading,
Steve
You need to use the predicate builder to create multiple OR queries, or AND queries.
The code below should work.
using (var s = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
var predicate = PredicateBuilder.True<SearchResultItem>();
foreach (var targetId in f.Targetids)
{
var tempTargetId = targetId;
predicate = predicate.Or(x => x.ItemId == tempTargetId)
}
rpt.DataSource = s.GetQueryable<SearchResultItem>().Where(predicate);
rpt.DataBind();
}

Windows Phone 7 Consuming Webservice WSDL

Ok I have written some basic generic webservices before but I have never tried to consume a 3rd party one.
The one I am trying to consume is
http://opendap.co-ops.nos.noaa.gov/axis/webservices/predictions/wsdl/Predictions.wsdl
I am not getting any results back from this what so ever and cannot figure out why.
More odd is it is not even reaching PredictionsClient_getPredictionsAndMetadataCompleted when I put a break point in the code it doesn't even reach it.
Any suggestions would be greatly appreciated
public void Bouy(double meters)
{
PredictionService.Parameters PredictionParams = new PredictionService.Parameters();
PredictionService.PredictionsPortTypeClient PredictionsClient = new PredictionService.PredictionsPortTypeClient();
GeoCoordinateWatcher gc = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
//gc.Position.Location.Latitude, gc.Position.Location.Longitude
GeoCoordinate myLocation = new GeoCoordinate(27.931631,-82.802582);
foreach (var bl in BouyLocation.GetAll())
{
GeoCoordinate otherLocation = new GeoCoordinate(bl.Lat, bl.Lon);
PredictionParams.beginDate = DateTime.Now.ToString("yyyyMMdd");
PredictionParams.endDate = DateTime.Now.AddDays(1.0).ToString("yyyyMMdd");
PredictionParams.stationId = bl.LocationID;
PredictionParams.timeZone = 0;
PredictionParams.unit = 1;
PredictionParams.dataInterval = 6;
PredictionsClient.getPredictionsAndMetadataCompleted += new EventHandler<PredictionService.getPredictionsAndMetadataCompletedEventArgs>(PredictionsClient_getPredictionsAndMetadataCompleted);
PredictionsClient.getPredictionsAndMetadataAsync(PredictionParams);
double mymeters = myLocation.GetDistanceTo(otherLocation);
if (mymeters < meters)
{
TextBlock DynTextBlock = new TextBlock
{
Name = "Appearance" + bl.LocationID,
Text = bl.LocationName + PredictionResult,
TextWrapping = System.Windows.TextWrapping.Wrap,
Margin = new Thickness(12, -6, 12, 0),
Style = (Style)Resources["PhoneTextSubtleStyle"]
};
DynamicAppearance.Children.Add(DynTextBlock);
this.nearByLocations.Add(new BouyLocationModel() { LocationName = bl.LocationName, LocationID = bl.LocationID, Lat = bl.Lat, Lon = bl.Lon });
}
}
var test = nearByLocations;
}
void PredictionsClient_getPredictionsAndMetadataCompleted(object sender, PredictionService.getPredictionsAndMetadataCompletedEventArgs e)
{
string err = e.Error.ToString();
PredictionResult = e.Result.ToString();
}
Loooking at the code you have here I think that you have used the importing of a ServiceReference to auto build the classes for you?
Unfortunately I have found that this is rather temperamental on WP7 and the only way I actually got it to work was when I connected it to a Microsoft WCF service. Connecting to anything else just doesn't work.
If you do google searches there are various pages talking about the fact it doesn't work and ways around it (which I couldn't get to work).
However, there are ways around it but it isn't as simple as the auto-generated stuff. Basically you do things manually.
Although there are other ways to manually create the web service what I did was follow the information in the following which worked well: http://zetitle.wordpress.com/2010/10/14/using-reactive-extensions-with-webrequest/
You will need to parse the response yourself but XML to LINQ works really well for this.
Hope that helps, or maybe someone will have the solution as it is something I am interested in knowing how to get working too

SharePoint web services: test if file exists

I'm using SharePoint web services in C#. I have my code working to check files and check them out using the Lists web service. I need to test to see if a file exists; I can find lots of examples for doing this using the object model API, but I can't seem to find a straightforward way of doing this using web services.
Try the Lists.GetListItems with a suitable CAML query.
A CAML query like
<Query><Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">Filename.rtf</Value></Eq></Where></Query>
should work; the field 'FileLeafRef' is where the filename is stored.
This code may do, it's a little rough, but demonstrates how to get a list of files based on the title.
public static bool PageExists(string listName, string webPath, string pageTitle)
{
string pageId = "";
IntranetLists.Lists lists = new IntranetLists.Lists();
lists.UseDefaultCredentials = true;
lists.Url = webPath + "/_vti_bin/lists.asmx";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + pageTitle + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
Guid g = GetWebID(webPath);
XmlNode items = lists.GetListItems(listName, string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, g.ToString());
}
return items.Count > 0;
}
public static XmlNodeList XpathQuery(XmlNode xmlToQuery, string xPathQuery)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlToQuery.OuterXml);
XmlNamespaceManager mg = new XmlNamespaceManager(doc.NameTable);
mg.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
mg.AddNamespace("z", "#RowsetSchema");
mg.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
mg.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois");
mg.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
mg.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory");
return doc.SelectNodes(xPathQuery, mg);
}
I also had similiar problems with this.
I have tried the following FieldRefs without success: "Name", "FileLeafRef" and "LinkFilenameNoMenu".
The post located at http://www.johanolivier.blogspot.com details what I had to do to get it working.