How to prevent users from embedding custom HTML - javascript

In my site, there is a div that gets updated dynamically by my system.
Through Ajax, that div contents is retrieved and sent to my server.
This is done through
$("div").find("script").remove();
var data = $("div").html();
////ajax request
How can I prevent users from adding their own HTML via inspect element, I've done so through the script tags but not sure how secure that is.
Note, the custom html must be removed, not converted into html entities or url encoded or something
I don't think there's a 100% secure way, but is there a way to make it difficult at least for users to do so.
If users add custom html through inspect element, it shouldn't be removed. Only when the ajax request is made, any custom html should be removed

Mutatiion Observer can help to prevent changing html via dev-tools.
However in my opion is better to expect correct data on backend side instead of attempts do something extra on frontend which is oftenly untrusted zone.

Related

Preventing passwords showing in source code

I am doing a password manager web app (like LastPass etc), one of the things that has occurred to me is that after using PHP to retrieve the passwords from a db and decrypting them and then using JS to display them in the UI, the variables containing their passwords are visible if someone looks at the source code. Even if I did not use JS and used echo instead it would still be in the source code. Does anyone know of a, hopefully not too complex, way that can prevent the passwords from being in the source code?
If you're talking about the HTML source code, this is normal. But there is a few way to avoid it:
If you just want not to have it in your HTML when it is received by the user, then you can implement it via an Ajax request in javascript, to update the DOM with the text.
If you want that when the user do inspect on the page he doesn't see the password you can use an input and set in javascript the value of it. then you set the input as disabled so the user cannot modify it. You can even change the type as password when needed so it's displayed as ****** when you want to hide it.
Another way could be to add in javascript a css :after and tu put the value inside it. But it will still be visible somewhere I think.
You can use JavaScript to send an HTTP request (using xhr or fetch) to your backend, then you can manipulate the DOM to show the password.

How to dynamically create css/js/html files and serve back at runtime with ASP.NET MVC

Ok, perfect examples: tryIt Editor (w3schools), jsbin, jsfiddle. I want a user to type css/js/html into different textareas, hit a magic button and poof, the output's displayed in an iframe.
Code examples are appreciated but I'm more after answers to how to go about it than exact implementation. For example, I can easily send the js / html / css as strings to the server. Then dynamically create files for them. But then what?
I want to have these files exist merely for the POST & GET. I dont want to remake a jsfiddle, I want to quickly show a user what output they have, not save it for later. So I dont want these files saved to memory. I want them sent to the user, and if they refresh the page then it's gone.
Is the idea of creating files (and removing the old ones each update) a good idea?
Should it all just be done client-side in javascript?
If using files is the correct method, how can I serve them up? I'm thinking create a file to a temp folder on the server, then POST the link, then send a DELETE request after 300ms with a unique ID + salt, which deletes the temp file if it still exists. But this is far from ideal I can think of a few issues immediately
Any server-side action method can technically return any kind of response. So instead of thinking about files, think about response types. Namely:
text/html
text/css
application/javascript (or maybe text/javascript?)
So you'd need at least three action methods. Pressing the "magic button" can, for example, reload a frame (with a POST request which includes the HTML/CSS/JS inputs) which:
invokes the action method which returns text/html, which itself:
includes standard tags in the head node which reference the routes for the CSS and JavaScript "files" (which aren't really files, just action responses)
One handy way to return custom responses from the action methods would be with the ContentResult type:
return Content(htmlText, "text/html");
Or:
return Content(cssText, "text/css");
So your server-side code can, for example, take the CSS text from the client-side and just echo it back like that. (Beware of various attacks, such as XSS. This simplistic implementation isn't likely ideal, but should get you started.) The only one you'd really need to wrap in any custom text would be the HTML response, where you can just statically define the HTML server-side and put the user-input HTML in just the body element.
So just thinking out loud, if the POST request for the frame/iframe consists of the three values, then the basic HTML server-side action might look like:
public GetHTML(string html, string css, string javascript)
{
// temporarily store the css somewhere server-side
// temporarily store the javascript somewhere server-side
// build the html response from static dressing around the user-input html
return Content(htmlString, "text/html");
}
The CSS/JS are stored in a temporary server-side location, possibly utilizing session state or any built-in temporary storage mechanism. After the above action returns its response, the browser will request the CSS/JS actions from the tags in that response, those are simple enough:
public GetCSS()
{
// if the temporary location (session?) has a css value
// get that value
// else
// get a default, likely empty value
return Content(cssString, "text/css");
}
// repeat for the javascript content

how to read a single HTML element from the server page, using Javascript

How can I use JavaScript to read the contents of a single element on the same page as the JavaScript without re-loading the entire page (just re-loading the one element)? The single element must be read from the page from the server, not the browser's copy of the page. This is because the server will dynamically change the element.
The page has...
HTML elements, like <p id="target_element">..<dynamically changing data>..</p>
How can my JavaScript go back and read the contents of "target_element" without reloading the entire page.
(The server will periodically change the "..<dynamically changing data>.." inside the element.
thanks.
If you are familiar with jQuery, there is a convenient method called load() that will do it for you.
With something like this, you would replace the content of the element with id "target_element", with the content that comes back from URL content.php.
$('#target_element').load('content.php #target_element');
If you don't want to use a library like jQuery, or similar, then you have some writing to do to get cross-browser support for your Ajax-request and so on. So a library is probably the easiest way to go about this. 
It sounds like what you need is for your web page to make an ajax call to your server that will fetch the desired data from the server and then dynamically modify the current page based on the results from that ajax call.
It would be best if your server was modified to return JSON with just the data you're interested in rather than downloading and parsing an entire web page just to get one piece out of it.
You'll probably want to use AJAX. Try using jQuery and its AJAX functions:
http://api.jquery.com/category/ajax/
Basically you want to do an AJAX call to your server. If this call should only change one element, you should add a script to your server, which only emits this one element. Then you may call this script from your client's browser using AJAX and replace the element in the browser's version of the page.

how to dynamically append data to form post without ajax OR input tags

I am analyzing header tags for submitting forms online in order to better understand how htmlhttp forms work- signing in to gmail, yahoo mail, and amazon, using the network tab of google developer tools, to view the http headers of requests and responses, and learn where they come from. I am seeing very peculiar behavior in my browser's (chrome)request headers when signing into amazon. The form data, always has the following two header names appended to the second and third to last places of the form data query: x=(some random number), and y=(some random number).
There are no input tags getting dynamically generated, since when i step through the code using breakpoints, none ever get added, and when i tell google chrome to break on all subtree modifications, the site still sends off the post with the added parameters before anything gets modified.
There also is NO ajax call which is causing dynamically added data to be appended to the form post, since google developer tools shows no ajax comes before the form post in the timeline of the network tab.
My question is this: is there any way, using javascript, to instruct a browser, to append data to a form post, WITHOUT the use of dynamically appended input elements, or ajax?
If you are talking about the x & y variables specifically, then it came from an <input type="image">. You could try playing with input type image and see how it behaves.
But for other cases (where you want to add any other variable) then I think the best way is to append input elements on the fly.

To build a `Delete` -button efficiently with JavaScript / PHP

Which of the following code is better in building a delete -action for removing a question?
1 My code
<a href='index.php?delete_post=777>delete</a>
2 Stack Overflow's code
<a id="delete_post_777>">delete</a>
I do not understand completely how Stack Overflow's delete -button works, since it points to no URL.
The id apparently can only be used by CSS and JavaScript.
Stack Overflow apparently uses JavaScript for the action.
How can you put start the delete -action based on the content of CSS -file by JavaScript?
How can you start a SQL delete -command by JavaScript? I know how you can do that by PHP, but not by JavaScript.
Your method is not safe as a user agent could inadvertently crawl the link and delete the post without user intervention. Googlebot might do that, for instance, or the user's browser might pre-fetch pages to speed up response time.
From RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
Naturally, it is not possible to
ensure that the server does not
generate side-effects as a result of
performing a GET request; in fact,
some dynamic resources consider that a
feature. The important distinction
here is that the user did not request
the side-effects, so therefore cannot
be held accountable for them.
The right way to do this is to either submit a form via POST using a button, or use JavaScript to do the deletion. The JavaScript could submit a hidden form, causing the entire page to be reloaded, or it could use Ajax to do the deletion without reloading the page. Either way, the important point is to avoid having bare links in your page that might inadvertantly be triggered by an unaware user agent.
Bind a click event on the anchor which start with "delete_post_" and use that to start an Ajax request.
$("a[id^='delete_post_']").click(function(e){
e.preventDefault(); // to prevent the browser from following the link when clicked
var id = parseInt($(this).attr("id").replace("delete_post_", ""));
// this executes delete.php?questionID=5342, when id contains 5342
$.post("delete.php", { questionID: id },
function(data){
alert("Output of the delete.php page: " + data);
});
});
//UPDATE
With the above $.post(), JavaScript code calls a page like delete.php?id=3425 in the background. If delete.php contains any output it will be available to you in the data variable.
This is using jQuery. Read all about it at http://docs.jquery.com/How_jQuery_Works.
The url you are looking for is in the js code. Personally I would have an id that identifies each <a> tag with a specific post, comment... or whatever, and then have a class="delete_something" on each one, this then posts to the correct place using javascript.
Like so:
Delete
<script type="text/javascript">
jQuery('a.delete_post').live('click', function(){
jQuery.post('delete.php', {id: jQuery(this).attr('id')}, function(data){
//do something with the data returned
})
});
</script>
You're quite correct that absent an href="..." attribute, the link would not work without JavaScript.
Generally, what that JavaScript does is use AJAX to contact the server: that's Asynchronous JavaScript and XML. It contacts a server, just as you would by visiting a page directly, but does so in the background, without changing what page the browser is showing.
That server-side page can then do whatever processing you require. In either case, it's PHP doing the work, not JavaScript.
The primary difference when talking about efficiency is that in a traditional model, where you POST a form to a PHP page, after finishing the request you must render an entire page as the "result," complete with the <head>, and with all the visible page content.
However, when you're doing a background request with AJAX, the visitor never sees the result. In fact, it's usually not even a human-readable result. In this model, you only need to transfer the new information that JavaScript can use to change the page.
This is why AJAX is usually seen as being "more efficient" than the traditional model: less data needs to travel back and forth, and the browser (typically) needs to do less work in order to show the data as part of the page. In your "delete" example, the only communication is "delete=777" and then perhaps "success=true" (to simplify only slightly) — a tiny amount of information to communicate for such a big effect!
It all depends on how your application is built, what happens at Stack Overflow is that the delete link click is caught by JavaScript and an Ajax request is being made to delete the post.
You can use a JavaScript library to easily catch clicks on all elements that match your selector rule(s).
Then you can use Ajax to send a request to the PHP script to do the SQL work.
On a side note, ideally you would not use GET for deleting entries, but rather POST, but that's another story.

Categories

Resources