I wrote a little program with node js and I used ejs as a template. In my program, I calculate two parameters 'msg1' and 'msg2' that I want to show on a modal window. Unfortunately I couldn't do that with ejs.
As I understand it, you're running the .ejs template on the server, not the client.
Anything inside <% %> runs as part of the template, which means it's trying to call alert in the server. This should fail.
You haven't said what msg1 and msg2 are. If they're client-side variables then all you need is:
function alertNumber() {
alert(msg1 + msg2)
}
which would mean you don't even need templating - it's just an HTML file. On the other hand, if msg1 and msg2 are server-side variables, they need to be inserted using the template. A naive way of doing so would be like this:
function alertNumber() {
alert('<%- msg1 + msg2 %>')
}
This only works if msg1 + msg2 doesn't contain the characters ', \, newline, carriage return, and possibly others I've missed. If it does, the script will probably fail. In particular, don't do this unless msg1 and msg2 are from a trusted source, because whoever controls them will be able to inject any javascript code they want into the client. However, if you can guarantee that they're numbers then this won't be a problem.
Last but not least... you've defined alertNumber. Have you actually used this function?
Related
so what I'm trying to do is pass a simple string variable that contains my error message in C# into my javascript function when I call the function. My function call works fine, but it keeps outputting the wrong thing. This might be important too, I'm calling the Response.Write pieces within my Global.asax.cs file and my javascript file is within my Scripts folder in my MVC project. Based on the research I've found, this is what I currently have after help from the comments:
function KickOutUnwantedUsers(aMesssage) {
console.log("Inside KickOutUnwantedUsers"); //for debugging
console.log(aMesssage); //for debugging
alert(aMessage);
window.open('', '_self').close();
}
It just continues to output this
<%=errorMessage%>
I'm not sure how to fix it, as everything I've found says to pass the variable that way, but I'm wondering if I need to pass it as an actual parameter into the function, and if so, how to do that.
UPDATE: Here is the C# code:
else
{
string user = s.Remove(0, 4);
string errorMessage = "THE FOLLOWING ERRORS MIGHT HAVE OCCURRED: " + user +
" has either been disabled or the account does not exist." +
" PLEASE CONTACT YOUR ADMINISTRATOR. ";
Response.Write("<script type=\"text/javascript\" src=\"Scripts/HelpfulFunctions.js\">");
Response.Write("</script>");
Response.Write("<script type=\"text/javascript\">");
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");
Response.Write("</script>");
}
SOLVED
#Igor was very helpful in the comments, and I did things as he suggested, which for some reason would not work at first, but then the following day I deletedmy JavaScript file, remade it under the same name and retyped out the javascript code and it worked. Coding is strange sometimes. I must've had a typo or something.
This is what the (badly documented) HttpUtility.JavaScriptStringEncode is for:
// the second argument "true" causes quotation marks to be inserted as well
var message = <%= HttpUtility.JavaScriptStringEncode(errorMessage, true) %>;
First. Such line as
var message = '<%=errorMessage%>';
only makes sense in ASP.NET markup file. In js file it is meaningless, since javascript files are not processed by ASP.NET server-side.
Second. Since you are passing message string as parameter, you need function signature to reflect this:
function KickOutUnwantedUsers(aMessage) {
alert(aMessage);
window.open('', '_self').close();
}
and - note the quotes around the parameter value:
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");
I know this is vulnerable as a hacker could embed an image that visits the site URL and do all sorts with the 'message' parameter:
<script>
var message = // get message parameter from URL, e.g domain.com?message=hello+there
document.write('Your message: ' + message);
</script>
...but is there any way a hacker could do anything with this (on its own without any other JS)?:
<script>
function displayMessage(message) {
document.write(message);
}
</script>
Obviously I could open a console in a browser and type anything in, but could a hacker invoke a JavaScript method somehow (with this code alone)?
I know the method could be invoked if the website also had the code at the very top, but can a method be invoked on its own?
Btw. I'm not exactly looking to do the above, it just helps me understand this.
What have I tried?
Read a lot of the docs on owasp.org
Googled terms such as “XSS - can you invoke a method”
http://excess-xss.com/
http://www.golemtechnologies.com/articles/prevent-xss#how-to-test-if-website-vulnerable-to-cross-site-scripting
Read many of the Similar Questions shown in the nav panel when typing this question
In the first code, message is an untrusted string which can contain malicious code. Parsing it as HTML may execute that code:
var message = '<img src="//" onerror="alert(\'You are pwned!\')" />';
document.write('Your message: ' + message);
The second code is different. It's just a function, it doesn't run anything by itself.
Of course, if you call it with an untrusted string, you will have the same problem than in the first one. Therefore, don't do that.
However, attackers can't call arbitrary functions. Well, if they can, it means you are already pwned, so it doesn't matter anymore. I mean, if an attacker has gained enough "privileges" to be able to call displayMessage, why bother calling it instead of calling document.write (or whatever) directly?
I am working inside a jquery, getJSON callback function using flask as my web framework.
I am trying to set the link desination for a dynamically created dom element. I want to set it to the jinja2 code for url_for. So, I would like to do something like this:
a.href ="{{ url_for('write_response', id=".concat(data.libArticles[i].id.toString(), ") }}");
I have had the worst time doing this. First, it would not recognize the "{{" and "}}" strings, removing them, opening quotes and doing other weird stuff because of those characters. Finally, by doing this:
var url1 = "{url_for('write_response', id=".concat(data.libArticles[i].id.toString(),")}");
var url2 ="{".concat(url1, "}");
a.href = url2;
it finally accepted the string with two instances of "{", so it accepted "{{somethig}}"
This still did not work and instead, when the link is clicked, it redirects to the following and fails :
http://localhost:5000/write_response/%7B%7Burl_for('write_response',%20id=3)%7D%7D
Does anyone know how to do this?
Your mixing up your python and javascript. Your first attempt failed, because your trying to execute javascript inside python. What's actually happening is everything, including the ".concat is being treated as the value for your id. Your second attempt is even more confused.
It's worth remembering that the python code gets executed on the server and then sent to the browser, the javascript gets executed after the fact in the browser. So the python/jinja code can't possibly know about the value of a javascript variable.
I think you should be able to do something like the following to get it to work:
var url = "{{ url_for('write_response') }}";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
Everything inside the set of {{ }} is considered jinja code, seperate from whatever is going on around it in the file. this should translate into the following in the browser:
var url = "/write-response";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
which should get you something like /write-response?id=12345
The encodeURLComponent(..) call just makes sure the value is url safe.
i m doing a database project using mysql as the database and jsp for my frontend part along with javascript and ajax for interaction.
Now the problem is i need to assign a java script variable which is having a string to a jsp variable.
I did this using the following statement?
<% String str="document.write(s)"; %>
where "s" is already defined as
<script type="text/javascript">
var s="hello world";
<script>
but i m getting error in the assignment statement(which is shown in bold above) as incorrect syntax?
the error i m getting is-
check the manual that corresponds to your MySQL server version for the right syntax to use near '<script>document.write(s)</script>'
what is the error in this stmt or is there any other method in doing this assignment?
Can anyone help in doing this?
You cannot do this. The JSP statement is executed server-side, before the execution of the Javascript statement, that is executed client-side after the browser received the http response.
It is not clear your goal, but if you only need to display in the page the value of a javascript variable, you can use:
trivial javascript:
document.write(s);
targeting existing element:
document.getElementById('myElementId').innerHTML = s;
using jQuery:
$('#myElementId').html(s);
If i understand correctly you are trying to build and execute a sql query based on user input that is handled by javascript. As ADC said this can not be done since jsp is executed server side therefore before browser executes javascript. What you can do is create the sql query and pass this as a parameter a different jsp/servlet (or the same if you can handle this case) which will execute the query
In the first page where sql statement is constructed in variable s you should put something like this
<script>
var s = "hello world";
function createLink(){
document.getElementById('mylink').href= 'page2.jsp?statement='+s;
}
window.onload=createLink;
</script>
<a id="mylink" href=""/>Click to exexute query</a>
which create a link to you second page (page2.jsp) passing the statement as parameter.
Now in page2.jsp you should retreive the parameter value like
<% String statement = request.getParameter("statement") %>
and then execute your query.
Even better you should use a servlet instead of a jsp page to perform the query. You could read a tutorial for jsp/sevlets to see how this can be done
eg. http://www.laliluna.de/articles/posts/first-java-servlets-jsp-tutorial.html
Using ASP.NET MVC + jQuery:
I need to use some values owned by the server in my client-side JavaScript.
Right now, I've temporarily got a script tag in the actual view like this:
<script>
var savePath = '<%= Url.Action("Save") %>';
</script>
But I want to move it into something cleaner and more maintainable. I'm thinking of something along the lines of creating a JavaScript controller/action and returning a JSON object that would contain all the data I need, then using the view as the src for a script tag.
Any other ideas?
This actually depends. For simple inliners, the line above works just fine. If you need a LOT of server data in the JavaScript, your view approach may work. However you'll get the same result if you just render partial view that outputs the required JavaScript.
There's a problem with this, since you may end up mixing server data with JavaScript. The best approach would be to minimize server data to absolute minimum, and pass it to JavaScript functions instead of mixing with JavaScript code. That is, not
function func() {
var path = '<%= Url.Action("my") %>';
$(".selector").append("<img src='" + path + "' />");
}
but
function AppendImageToSelector(path) {
$(".selector").append("<img src='" + path + "' />");
}
function func() {
var path = '<%= Url.Action("my") %>';
AppendImageToSelector(path);
}
This makes the code cleaner and easier to understand, helps to move JavaScript out to separate .js files, helps to re-use JavaScript when needed, and so on.
If you need a lot of server-related URLs in JavaScript, you may want to create global (in master page) function like
function url(relative) {
return '<%= Url.Content("~") %>' + relative;
}
and use it from JavaScript scripts. This technique is questionable, though; for example it doesn't use MVC routing rules so URLs may not be out of sync; etc.
I know this is not applicable in all cases but when I need to pass an Url to a client script (as in your example) it is often to ajaxify some anchor or button I already have in the DOM:
<%= Html.ActionLink("Save data", "save") %>
and in my script:
$('a').click(function() {
$.get(this.href);
return false;
});
Stephen Walther - ASP.NET MVC Tip #45 – Use Client View Data