With the intention of this blog XSS Prevention in UI5 I escaped the post parameters to avoid xss statements in my database. Next time if I get the information everything works, but it will also escapes non-script strings like this:
before escaping
after escaping
The alert command was escaped, but this kind of output is not human readable. How can I handle this? Is it possible to escape only javascript?
I could convert it back to readable string. In this case the alert will work again. What is the best practise for this case?
jQuery.sap.escapeHTML("<here><are><some></html></tags>");
Output:
<here><are><some></html></tags>
HTML will convert >, < and / automatically into </>, so you prevented XSS.
or just use simple jQuery Style:
var someHtmlString = "<script>alert('hi!');</script>";
$("#mySelector").text(someHtmlString);
Related
How to deal with this code ?
Data is read from document.location and passed to $() via the following statements:
var url = document.location.toString();
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
The question is this case would be what could come after the # in the URL. Most browsers will URL-encode special chars, but there may still be ways to get around it, especially in legacy browsers.
Regardless of that, I think it's a good idea to validate data before you use it. If you can restrict the accepted values to let's say a-z (and possibly numbers and dashes), there shouldn't be a way to exploit it.
var tab = document.location.toString().split('#')[1];
if (tab && !/[^a-zA-Z0-9]/.test(tab)) $('.nav-tabs a[href="#' + tab + '"]').tab('show');
I've been trying to prohibit users from entering double-quotes (") into some fields that are used in JSON strings, as they cause unexpected termination of values in the strings. Unfortunately, while the regex isn't hard to write, I can't get it to work within XPages.
I tried using both double-quotes alone and using the escape character. Both ways fail any string, not just ones including the double-quotes.
<xp:validateConstraint message="Please do not use double quotes in organization/vendor names">
<xp:this.regex><![CDATA['^[^\"]*$]]></xp:this.regex>
</xp:validateConstraint>
There must be a simple way around this issue.
I think you're running into issues with your regex property for your xp:validateConstraint validator. You seem to be attempting to strip the characters in the xp:this.regex as opposed to specifying what characters are allowed, as I believe the docs read. I might recommend checking out the xp:customConverter (bias: I'm more familiar with the customConverter) which gives you the ability to alter the getValueAsObject and getValueAsString methods; then you can escape the undesired characters.
Here's what I'm thinking of, to strip them out. If you plug this into an XPage, you'll find that when the value is pulled (e.g.- by the partial refresh), it converts the input content accordingly by stripping out quotes (both single and double, in my case).
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:inputTextarea
id="inputTextarea1"
value="#{viewScope.myStuff}"
disableClientSideValidation="true">
<xp:this.converter>
<xp:customConverter>
<xp:this.getAsString><![CDATA[#{javascript:return value.replace(/["']/g, "");}]]></xp:this.getAsString>
<xp:this.getAsObject><![CDATA[#{javascript:return value.replace(/["']/g, "");}]]></xp:this.getAsObject>
</xp:customConverter>
</xp:this.converter>
</xp:inputTextarea>
<xp:button
value="Do Something"
id="button1">
<xp:eventHandler
event="onclick"
submit="true"
refreshMode="partial"
refreshId="computedField1" />
</xp:button>
<xp:text
escape="true"
id="computedField1"
value="#{viewScope.myStuff}" />
</xp:view>
My interaction with the above code yields:
Notice that for it to reflect in the refresh, I'm modifying both the getAsString and the getAsObject, since it's updating the viewScope'd object during the refresh (a fact I had to remind myself of), but saving to a text field in XPages will get the value by the getAsString (provided your data source knows its a String related field, e.g.- NotesXspDocument as document1, with known Form, where the field is a Text field).
As the above comments alluded to, this performs an act of filtering the input values as opposed to escaping or validating those values. You could also change my replace methods to replacing with a text escape character, return value.replace(/"/g,"\"").replace(/'/g,"\'");.
Is the simple answer just add a JavaScript function call on the submit button to remove the quote?
A more elegant solution would be to not allow typing of the quote by checking the keydown event and preventing for that character code. The user should not be able to type one thing and then have it changed on them in processing
#Eric McCormick recommends a customConverter which in my opinion is a neat solution I probably would be going for in many cases. Sometimes however we need to teach users to adhere to the rules so we have to show them where they did wrong. That's when we may need a validator.
Playing around a bit the simplest solution I came up with is a xp:validateExpression simply looking for the first occurrence of a double quote within the String entered:
<xp:inputText
id="inputText1"
value="#{viewScope.testvalue}">
<xp:this.validators>
<xp:validateExpression
message="Hey, wait! Didn't I tell you not to use double quotes in here?">
<xp:this.expression><![CDATA[#{javascript:value.indexOf("\"")==-1}]]></xp:this.expression>
</xp:validateExpression>
</xp:this.validators>
</xp:inputText>
If that's a single occurrence in your application that's it, really. If you need this and similar solutions all over the place you might want to take a look into writing a small validator bean (java), register it via faces-config.xml and then use it everywhere in your application e.g by using an xp:validator instead
As suggested by #Tomalik and #sidyll, this is attempt to solve the wrong problem. While each of the answers supplied do solve the problem of preventing the user from entering undesirable characters, it is better to encode those characters to preserve the user's input. In this particular case, the intermediate step in providing the data to the user via a JSON string is to pull the value from a view.
So, all I had to do was change the column formula to encode the string using the UTF-8 character set and it displays the values with the "undesirable characters". The unencoded value is stored on the document so that Old Notes access won't create confusion.
#URLEncode ("UTF-8"; vendorName )
In one case, the JSON is computed as part of the form design, but the same solution works.
Working on one of the tasks i am using jsstringformat function to handle json data if some special characters are used, but that does not seems to handle all issues.
My JSON still breaks.
I am using like this :
"<a href='edit.cfm?id=#jsStringFormat(qFiltered.randomnumber)#' style='color:##066D99'>#trim(jsStringFormat(qFiltered[thisColumn][qFiltered.currentRow]))#</a>"
I am lost here what else i can use as any part of regex or rereplace that it should not break
Thanks
You're doing multiple things here.
You're putting the string into a URL: use UrlEncodedFormat.
You're also putting it in an HTML tag: use HtmlEditFormat.
The whole thing is going into a JavaScript variable, so I would use JSStringFormat to wrap the whole thing.
Try building your string before assigning it.
<cfsavecontent variable="htmlLink"><cfoutput>
#HtmlEditFormat(Trim(qFiltered[thisColumn][qFiltered.currentRow]))#
</cfoutput></cfsavecontent>
myJsVar = "#JsStringFormat(Trim(htmlLink))#";
To me regular expression validation seems straight forward and meaningfull rather than validating everything with asp.net validation controls. I am learning asp.net and do not want to memorize all asp.net validation controls, when any form input can be simply validated with reqular expression. Am I thinking right or should I use validation controls?
Example:`RequiredFieldValidator vs Regex Solution C#
if(TextBox1.Text == ""){
Label1.text = "Name Field is required, Please try again";
return;
}
CompareValidator vs Regex Solution
if(Regex.IsMatch(TextBox1.Text, #"^[0-9]")){
if(Convert.ToInt32(TextBox1.Text) > 18){
output.InnerHtml = #"some code";
} else{
Label1.Text = "You should be old enough to express out your political views ";
return;
}
} else{
Label1.Text = "You should be old enough to express out your political views";
return;
}
}
`
Thinking would not be better to do everything in C#, rather than remembring all those validation controls
The major advantage to the validation controls is that in most cases they will output JavaScript validation for the client side that matches the server-side validation. This can reduce round trips to the server which is always a benefit. However, if you're good with JavaScript, you can probably code the client side piece more efficiently than the control would output anyway.
One other thing to consider, when using the control you can turn the validation on/off on both client and server using one flag on the control, if using your own code, you have to handle those separately.
You are right, regular expression validator can replace a lot of other validators, provided you can write a validation expression that works well on client and server side.
You can do a lot of validation work in regular expressions, but there are some areas where regexes are not ideal:
date validation: Either you get a terribly unwieldy regex, or you'll miss lots of plausible but illegal dates (like Feb 29, 2000).
email validation. Same thing here - you either reject some valid addresses, or you allow invalid addresses (and in either case, you'll allow addresses that are syntactically OK but don't correspond to an actual mailbox).
number validation in general - regular expressions are good for matching textual data. Using them to validate numbers is cumbersome and error-prone. Have you thought of exponential notation, locale-dependent decimal separators, thousands separators, leading zeroes, etc...?
Apart from that, the JavaScript regex engine has some limitations (e. g., lack of lookbehind assertions) that you need to know about when trying to write regexes that have to work both on the client and the server side.
And finally, do you realize that there's an error in your example regex? Maybe using a validator is safer unless you really know how to build a regex that does exactly what you intend it to do...
It's a bit late, but I'm disappointed in myself for not coming up with something more elegant. Anyone have a better way to do this...
When you pass an OAuth code to Facebook, it response with a query string containing access_token and expires values.
access_token=121843224510409|2.V_ei_d_rbJt5iS9Jfjk8_A__.3600.1273741200-569255561|TxQrqFKhiXm40VXVE1OBUtZc3Ks.&expires=4554
Although if you request permission for offline access, there's no expires and the string looks like this:
access_token=121843224510409|2.V_ei_d_rbJt5iS9Jfjk8_A__.3600.1273741200-569255561|TxQrqFKhiXm40VXVE1OBUtZc3Ks.
I attempted to write a regex that would suffice for either condition. No dice. So I ended up with some really ugly Ruby:
s = s.split("=")
#oauth = {}
if s.length == 3
#oauth[:access_token] = s[1][0, s[1].length - 8]
#oauth[:expires] = s[2]
else
#oauth[:access_token] = s[1]
end
I know there must be a better way!
Split on the & symbol first, and then split each of the results on =? That's the method that can cope with the order changing, since it parses each key-value pair individually.
Alternatively, a regex that should work would be...
/access_token=(.*?)(?:&expires=(.*))/
If the format is strict, then you use this regex:
access_token=([^&]+)(?:&expires=(.*))?
Then access_token value is in \1, and expires, if there's any, will be in \2.
Query string parsing usually involves these steps:
If it is a complete URL, take the part after the first ?
split the rest on &
for each of the resulting name=value pairs, split them on =
URL-decode to the value and the name (!)
stuff the result into a data structure of your liking
Using regex is possible, but makes invalid assumptions about the state of URL-encoding the string is in and fails if the order of the query string changes, which is perfectly allowed and therefore cannot be ruled out. Better to encapsulate the above in a little parsing function or use one of the existing URL-handling libraries of your platform.