this is my HTML
<div id="remove">Username</div>
and this is my JS code
function slice() {
var t = document.getElementById("remove");
t.textContent = t.textContent.slice(0, -3);
}
slice();
Username load from foreach
{foreach from=$last_user item=s}
{$s.date}
{$s.username}
{/foreach}
This code working and remove 3 letter but when right click on browser and look at page sources i can see "Username" !
I need remove three letter because of privacy and security .
something like
*** name or usern ***
Thank for help me !
The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know.
You'll need to fix this on your backend - either hard-code in
<div id="remove">Usern</div>
or, for a more dynamic approach, use a template engine (or whatever's generating the HTML) and look up how to change strings with it. For example, in EJS, if user is an object with a username property, you could do
<div id="remove"><%= user.username.slice(0, -3) %></div>
Changing the content only with client-side JavaScript will not be sufficient, if you wish to keep some things truly private.
With Smarty, you can define a modifier that takes a string and returns all but the last three characters of it.
function smarty_modifier_truncate_three($string)
{
return substr($string, 0, -3);
}
and then in your template, replace
{$s.username}
with
{$s.username|truncate_three}
If you want only the first three characters, it's easier because you can use the built-in truncate.
{$s.username|truncate:3}
JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters.
Related
I have a page that lists out items according to numerous parameters ie variables with values.
listitems.php?color=green&size=small&cat=pants&pagenum=1 etc.
To enable editing of the list, I have a parameter edit=1 which is appended to the above querystring to give:
listitems.php?color=green&size=small&cat=pants&pagenum=1&edit=1
So far so good.
When the user is done editing, I have a link that exits edit mode. I want this link to specify the whole querystring--whatever it may be as this is subject to user choices--except remove the edit=1.
When I had only a few variables, I just listed them out manually in the link but now that there are more, I would like to be able programmatically to just remove the edit=1.
Should I do some sort of a search for edit=1 and then just replace it with nothing?
$qs = str_replace("&edit=1, "", $_SERVER['QUERY_STRING']);
<a href='{$_SERVER['PHP_SELF']}?{$qs}'>return</a>;
Or what would be the cleanest most error-free way to do this.
Note: I have a similar situation when going from page to page where I'd like to take out the pagenum and replace it with a different one. There, since the pagenum varies, I cannot just search for pagenum=1 but would have to search for pagenum =$pagenum if that makes any difference.
You can use parse_str() to parse the query string, remove the unwanted parts and build the new one via http_build_query() like this
parse_str($_SERVER['QUERY_STRING'], $params);
unset($params['edit']);
$new_query_string = http_build_query($params);
So I'm currently using CF11 and CFWheels 1.1, the "Global Script Protection"(GSP) server feature does an awful job of covering the XSS bases. I would like to extend it to block any and all tags/vectors for JS from being inserted into the database.
CF11 offers antiSamy protection via the getSafeHTML() function which applies a xml policy file specified in application.cfc but I would still need to modify every single varchar cfqueryparam in the application to use it right?
Is there a way to get CF11 to enable the antisamy features server or application wide in a similar way that the GSP feature works? What I mean by this is GSP automatically strips tags out of input submitted to the app without having to modify all the queries/form actions. I'd like a way to apply the antisamy policy file or getSafeHTML() in the same way.
Thanks!
Why would you have to apply it to every one? You would only need to do it for string (varchar) inputs and only when inserting. And even then, you wouldn't use it everywhere. For example, if you ask for my name and bio, there is no reason why you would want html, even "good" html, in my name. So I'm sure you already use something there to escape all html or simply remove it all. Only for a field like bio would you use getSafeHTML.
Validation is work. You (typically) don't want a "all at once" solution imo. Just bite the bullet and do it.
If you did want to do it, you can use onRequestStart to automatically process all keys in the form and url scope. This is written by memory so it may have typos, but here is an example:
function onRequestStart(string req) {
for(var key in form) { form[key] = getSafeHTML(form[key]); }
for(var key in url) { url[key] = getSafeHTML(url[key]); }
}
I agree with Ray, validation is work, and it is very important work. If you could have a server wide setting it would be way to generalized to fit all situations. When you do your own validation for specific fields you can really narrow down the attack surface. For example, assume you have a form with three fields; name, credit card number, social security number. With one server wide setting it would need to be general enough to allow all three types of input. With your own validation you can be very specific for each field and only allow a certain set of characters; name - only allows alpha characters and space, credit card number - only allows digits, space, dash and must conform to the mod rule, social security number - only allows digits and dash in 3-2-4 format. Nothing else is allowed.
That being said, I just wanted to point out that the "Global Script Protection" rules can be customized. That setting works by applying a regular expression that is defined in the cf_root/lib/neo-security.xml file in the server configuration, or the cf_root/WEB-INF/cfusion/lib/neo-security.xml file in the JEE configuration to the variable value. You can customize the patterns that ColdFusion replaces by modifying the regular expression in the CrossSiteScriptPatterns variable.
The default regular expression is defined as:
<var name='CrossSiteScriptPatterns'>
<struct type='coldfusion.server.ConfigMap'>
<var name='<\s*(object|embed|script|applet|meta)'>
<string><InvalidTag</string>
</var>
</struct>
</var>
Which means, by default, the Global Script Protection mechanism is only looking for strings containing <object or <embed or <script or <applet or <meta and replacing them with <InvalidTag. You can enhance that regular expression to look for more cases if you want.
See Protecting variables from cross-site scripting attacks section on this page
The solution as implemented for a cfwheels 1.1 app:
I used the slashdot file from https://code.google.com/p/owaspantisamy/downloads/list
This goes in application.cfc:
<cfcomponent output="false">
<cfset this.security.antisamypolicy="antisamy-slashdot-1.4.4.xml">
<cfinclude template="wheels/functions.cfm">
</cfcomponent>
This goes in the /ProjectRoot/events/onrequeststart.cfm file
function xssProtection(){
var CFversion = ListToArray(SERVER.ColdFusion.productversion);
if(CFversion[1]GTE 11){
for(var key in form) {
if(not IsJSON(form[key])){
form[key] = getSafeHTML(form[key]);
}
}
for(var key in url) {
if(not IsJSON(url[key])){
url[key] = getSafeHTML(url[key]);
}
}
}
}
xssProtection();
This has been a question I've had since I started doing serious ajax stuff. Let me just give an example.
Let's say you pull a regular HTML page of a customer from the server. The url can look like this:
/myapp/customer/54
After the page is rendered, you want to provide ajax functionality that acts on this customer. In order to do this, you need to send the id "54" back to the server in each request.
Which is the best/most common way to do this? I find myself putting this in hidden form forms. I find it easy to select, but it also feels a bit fragile. What if the document changes and the script doesn't work? What if that id gets duplicated for css purposes 3 months from now, and thus breaks the page since there are 2 ids with the same name?
I could parse the url to get the value "54". Is that approach better? It would work for simple cases repeatedly. It might not work so well for complex cases where you might want to pass multiple ids, or lists of ids.
I'd just like to know a best practice - something robust that is clean, elegant and is given 2-thumbs up.
I think the best way to do this is to think like you don't have Ajax.
Let's say you have a form which is submitted using Ajax. How do you know what URL to send it to?
The src attribute. Simply have your script send the form itself. All the data is in the form already.
Let's say you have a link which loads some new data. How do you know the URL and parameters?
The href attribute. Simply have the script read the URL.
So basically you would always read the URL/data from the element being acted upon, similar to what the browser does.
Since your server-side code knows the ID's etc. when the page is being loaded, you can easily generate these URLs there. The client-side code will only need to read the attributes.
This approach has more than just one benefit:
It makes it simpler where the URLs and data is stored, because they are put exactly in the attributes that you'd normally find then in HTML.
It makes it easier to make your code work without JavaScript if you want to, because the URLs and all are already in places where the browser can understand them without JS.
If you're doing something more complex than links/forms
In a case where you need to allow more complex interactions, you can store the IDs or other relevant data in attributes. HTML5 provides the data-* attributes for this purpose - I would suggest you use these even if you're not doing HTML5:
<div data-article-id="5">...</div>
If you have a more full-featured application on the page, you could also consider simply storing your ID in JS code. When you generate the markup in the PHP end, simply include a snippet in the markup which assigns the ID to a variable or calls a function or whatever you decide is best.
Ideally your form should work without javascript, so you probably have a hidden form input or something that contains the id value already. If not, you probably should.
It's all "fragile" in the sense that a small change will affect everything, not much you can do about that, but you don't always want to put it in the user's hands by reading the url or query string, which can be easily manipulated by the user. (this is fine for urls of course, but not for everything. Same rules that apply to trusting $_GET and query strings apply here).
Personally, I like to build all AJAX on top of existing, functional code and I've never had a problem "hooking" into what is already there.
Not everything is a form though. For
example, let's say you click a "title"
and it becomes editable. You edit it,
press enter, and then it becomes
uneditable and part of the page again.
You needed to send an ID as part of
this. Also, what about moving things
around and you want those positions
updated? Here's another case where
using the form doesn't work because it
doesn't exist.
All of that is still possible, and not entirely difficult to do without javascript, so a form could work in either case, but I do indeed see what you're saying. In almost every case, there is some sort of unique id, whether it's a database id or file name, that can be used as the "id" attribute of the html that represents it. * Or the data- attribute as Jani Hartikainen has mentioned.
For instance, I have a template system that allows drag/drop of blocks of content. Every block has an id and every area that it can get dropped has one as well. I will use prefixes on the containing div id like "template-area_35" or "content-block_264". In this case, I don't bother to fallback w/o javascript, but it could be done (dropdown-> move this to area for example). In any case, it's a good use of the id attribute.
What if that id gets duplicated for
css purposes 3 months from now, and
thus breaks the page since there are 2
ids with the same name?
If that happens (which it really shouldn't), someone is doing something wrong. It would be their fault if the code failed to work, and they would be responsible. Ids are by definition supposed to be unique.
IMHO putting is at a request parameter (i. e. ?customerId=54) would be good 'cos even if you can't handle AJAX (like in some old mobile browsers, command-line browsers and so) you can still have a reference to the link.
Apparently you have an application that is aware of the entity "Customer", you should reflect this in your Javascript (or PHP, but since you're doing ajax I would put it in Javascript).
Instead of handmaking each ajax call you could wrap it into more domain aware functions:
Old scenario:
var customer_id = fetch_from_url(); // or whatever
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
New scenario:
var create_customer = function (customer_id) {
return {
"dosomething" : function () {
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
},
"dosomethingelse": function () {
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
}
};
}
var customer_id = fetch_from_url(); // or whatever
var customer = create_customer(customer_id);
// now you have a reference to the customer, you are no longer working with ids
// but with actual entities (or classes or objects or whathaveyou)
customer.dosomething();
customer.dosomethingelse();
To round it up. Yes, you need to send the customer id for each request but I would wrap it in Javascript in proper objects.
I'd like to start by saying that my code is working perfectly, this is more a "how best to do it" kind of question.
So I have code like this in my .aspx file:
function EditRelationship() {
var projects=<%= GetProjectsForEditRelationship() %>;
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
var rels=<%= GetRelationshipsForEditRelationship() %>;
// etc
}
Again, it's working fine. The problem is that VS2008 kinda chokes on code like this, it's underlining the < character in the tags (with associated warnings), then refusing to provide code completion for the rest of the javascript. It's also refusing to format my document anymore, giving parsing errors. The last part is my worst annoyance.
I could put some of these in evals I guess, but it seems sorta dumb to add additional layers and runtime performance hits just to shut VS up, and it's not always an option (I can't remember off the top of my head where this wasn't an option but trust me I had a weird construct).
So my question is, how do you best write this (where best means fewest VS complaints)? Neither eval nor ajax calls fit this imo.
If your aim is to reduce VS complaints, and if you are running asp.net 4 (supporting Static client Ids), maybe a strategy like the following would be better?
Create a ASP:HiddenField control, set its ClientIdMode to "Static"
Assign the value of GetRelationshipsForEditRelationship() to this field on page load
In your javascript, read the value from the hidden field instead, I assume you know how to do this.
It's more work than your solution, and you will add some data to the postback (if you perform any) but it won't cause any VS complaints I guess :)
You could do this from your page in the code-behind
ClientScript.RegisterArrayDeclaration("projects", "1, 2, 3, 4");
or to construct something like JSON you could write it out
ClientScript.RegisterClientScriptBlock(GetType(), "JSONDeclarations", "your json stuff");
UPDATE Based on my comment
<script id="declaration" type="text/javascript">
var projects=<%= GetProjectsForEditRelationship() %>;
var rels=<%= GetRelationshipsForEditRelationship() %>;
</script>
<script type="text/javascript">
function EditRelationship() {
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
}
</script>
I don't have VS2008 installed to test with, so take this with a grain of salt, but have you tried something like this?
var projects = (<%= GetProjectsForEditRelationship() %>);
Something like that might trick the JavaScript parser into ignoring the content of your expression.
For what it's worth, VS2010 correctly parses and highlights your original code snippet.
Is it an option to move this to VS2010? I just copied and pasted your code and the IDE interpreted it correctly.
The best solution is to put javascript in a separate file and avoid this entirely. For this particular function, you're doing server-side work. Why not build the list of options that you intend to add dynamically in codebehind, put them in a hidden div, and then just have jQuery add them from the already-rendered HTML?
If you have a situation where you really want to dynamically create a lot javascript this way, consider using ScriptManager in codebehind to set up the variables you'll need as scripts and register them, then your inline script won't need to escape
ScriptManager.RegisterClientScript("projects = " + GetProductsForEditRelationship());
(Basically, that is not the complete syntax, which is context dependent). Then refer to "projects" in your function.
(edit)
A little cleaner way to do this on a larger scale, set up everything you need like this in codebehind:
string script = "var servervars = {" +
"GetProductsForEditRelationship: " + GetProductsForEditRelationship() +
"GetRelationshipsForEditRelationship: " + GetRelationshipsForEditRelationship() +
"}"
and refer to everything like:
servervars.GetProductsForEditRelationship
If you do this a lot, of course, you can create a class to automate the construction of the script.
I run into this problem constantly while developing AJAX applications. Let's say I want users to be able to click on a "flag" icon associated with each comment on my site, which results in an AJAX request being sent to the server, requesting that the comment be flagged. I need to associate a comment id with the comment on the client side so that the AJAX request may communicate to the server which comment to flag.
This page explains a number of ways to annotate HTML in this manner, but none of them are very satisfactory. While I could just use an id or class attribute to associate the comment id with the flag button (e.g. id="comment_1998221"), this fails with more complex data that doesn't fit well into those attributes (e.g. arbitrary strings). Is there a best practice for this sort of thing? Every time I need to do this, I end up with some kludge like using the id attribute, a hidden form field, or worse yet a span set to display:none.
The HTML5 data-* attributes seem like a perfect solution, but I've seen a lot of animosity toward them, which makes me think that people must already have a solution they're happy with. I'd love to know what it is.
This page explains a number of ways to annotate HTML in this manner, but none of them are very satisfactory.
Still, they are pretty much all you've got. Although that page isn't a terribly good summary, there are errors and it misunderstands what ‘unobtrusive’ JavaScript means.
For example it is in fact perfectly valid to put a script element inside body — just not directly inside a table element. You could put all the script fragments at the bottom of the table, or put each row in its own table, or even, with some limitations if you are intending to mutate the DOM, inside the row in question.
Setting “id="comment-123"” then scanning for all rows with an id starting with ‘comment-’ is indeed good for your particular case. For setting non-identifying extra info attributes, you could use either HTML5 data-attributes or hack it into the classname using eg. “class="comment type-foo data-bar"”. Of course both IDs and classnames have their limits about what characters you can use, but it's possible to encode any string down to valid strings. For example, you could use a custom URL-style encoding to hide non-alphanumeric characters:
<tr class="greeting-Hello_21_20_E2_98_BA">
...
</tr>
function getClassAttr(el, name) {
var prefix= name+'-';
var classes= el.className.split(' ');
for (var i= classes.length; i-->0;) {
if (classes[i].substring(0, prefix.length)==prefix) {
var value= classes[i].substring(prefix.length);
return decodeURIComponent(value.split('_').join('%'));
}
}
return null;
}
var greeting= getClassAttr(tr, 'greeting'); // "Hello! ☺"
You can even store complex non-string values in this way, by encoding them JavaScript or JSON strings then retrieving them using exec (or JSON.parse where available).
However, if you are putting anything non-trivial in there it soon gets messy. That's where you may prefer comments. You can fit anything in here except the sequence '--', which is easily escaped if it happens to come up in a string.
<table>
<tr class="comment">
<td>...</td>
<!-- {"id": 123, "user": 456} -->
</tr>
</table>
function getLastComment(node) {
var results= [];
for (var i= node.childNodes.length; i-->0;)
if (node.childNodes[i]==8)
return node.childNodes[i];
return null;
}
var user= getLastComment(tr).user;
The summary warns that this may not be guaranteed to work because XML parsers may discard comments, but then DOM Level 3 LS parsers must keep them by default, and every browser and major XML library so far does.
jQuery data API is nice for this.
Suppose you have the following DOM...
<div class="comment">
Flag
Some text
</div>
Then, assuming you are also loading these elements by ajax, you can do
$(".comment").data('someKey', (any javascript value/object));
Then later, upon click handler to the flag, you can do...
$(".flagSelector").click(function(ev) {
var extraData = $(this).closest(".comment").data("someKey");
// use extraData along with your request
});
If you are generating the comments on the server side and shipping them with the initial page, you need to figure out how to initialize the data. One way would be to have unique ID-s for the comment and upon pageload, still load the custom data from the server by Ajax.
Here is how I would do this:
When rendering the page server-side, generate the flag link as a normal link, so that it would work fine if you didn't have javascript enabled.
<a class="flag_link" href="/comment/123/flag/"><img src="flag.gif" /></a>
Then, in the javascript, add a click event to do this by ajax instead. I'll use jQuery for my example, but the same thing is not hard to do without it.
<script>
$('a.flag_link').click(function() {
$.get($(this).attr('href'), function() {
alert('you flagged this comment');
});
});
</script>
Of course, you'll do something more user-friendly than an alert to signal success.