Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    78
    Thanks
    2
    Thanked 0 Times in 0 Posts

    can you kill self-executable code in a form

    Hi All,

    Not sure how to ask this correctly so hope you follow.

    If you have a form and it submits a textarea input field to the host server that is fine for general text for a site. However, what if someone included self-executable code in the form of a script using a time out to run the execute function somehow, if that were possible.

    Can some sort of javascript code be used to kill the added code before the form is submitted.

    I ask this as I heard of someone who had a form to do something and obviously the sent data could be seen by others in a web page or something, the comment I heard was that when others saw the content on their PC the function mentioned above executed and sent them off to spam sites and such.


    Martin.

  • #2
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    I think what you are referring to is what is known as a cross-site scripting (XSS) attack:

    http://en.wikipedia.org/wiki/Cross-site_scripting

    Basically, if you have a user registration system for a forum such as this, let's say... And then let's say a user registered themselves as some_user_<script type='javascript'>alert('who farted?!');</script>name and the forum code didn't filter the input properly to prevent this, and so allowed this user name to be created and stored in the database. And then let's say the rest of the forum code simply outputs, verbatim, user names to the web page where they are called for. What does this do?

    Well, the <script></script> section would not be visible to users because the browser would, rightly, parse it as a script tag and process any javascript therein. So the visible user name would just be some_user_name but it would have a payload visible only from looking at the page's source code.

    In a case such as this, any time ANY user visits a page where this user name is displayed they will see an alert box. Well, replace that harmless alert with some actually malicious code and you have a real problem on your hands as the webmaster of said forum. Your users are being exposed. The script could, for example, send the malicious user the target's login information for the forum (or anything else a compromised web page on that website has access to for a user - this is especially dangerous for cookies).

    So in your friend's story, the code being executed was not on the malicious user's end. It was on everyone else's end. The way to stop such code from running is to simply strip or convert HTML special characters before outputting anything a user has provided (so, basically, most anything you pull from a database). In PHP it is as simple as using the htmlspecialchars() function. I'm not an ASP guy or anything so I'm not sure if they have a built-in function or not, but in any case it's pretty simple to build your own if you have to.

    It also helps to filter the data before even storing it to a DB in the first place. Determine if it's really necessary to even allow the HTML brackets <> at all, for example. Combine a front-end validation scheme with a back-end string conversion to keep HTML from being added to your page and you should be in good shape.

    But in terms of a pure javascript solution to this type of thing? No, I don't believe there is anything client-side that you could do to kill this entirely.
    Last edited by Rowsdower!; 05-30-2013 at 01:38 PM. Reason: Added detail
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    you can box the data FROM the DB, scrubbing it before it's shown to users as live markup, but you cannot scrub data on the way TO the DB, since JS can be over-written using the browser console.


    http://php.net/manual/en/function.my...ape-string.php
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by rnd me View Post
    you can box the data FROM the DB, scrubbing it before it's shown to users as live markup, but you cannot scrub data on the way TO the DB, since JS can be over-written using the browser console.
    http://php.net/manual/en/function.my...ape-string.php
    Hopefully, by now you reaslize that RndMe's answer is *ONLY* applicable to client-side JavaScript.

    Of course you can scrub the data on the way to the DB! You just have to do it with server-side code, *NOT* with JavaScript.

    One easy way to do this would be to simply remove all HTML tags from the data. But a simpler and often more reasonable way would be to just have the server *REJECT* any input that contains HTML tags: Send the user back to the input <form> with instructions to stop trying to put tags in his/her input.

    But I don't understand RndMe's reason for mentioning mysql_real_escape_string. What does it have do with anything, in this case? Yes, it will allow you to safely store the input into the database, preventing SQL Injection. But it won't in any way protect you against storing HTML tags--including <script> tags--in the database.

    Now, if you don't have control of the server-side code, you may have problems. Hopefully that is not the case.
    Last edited by Old Pedant; 05-30-2013 at 08:07 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    Quote Originally Posted by Old Pedant View Post
    But I don't understand RndMe's reason for mentioning mysql_real_escape_string. What does it have do with anything, in this case? Yes, it will allow you to safely store the input into the database, preventing SQL Injection. But it won't in any way protect you against storing HTML tags--including <script> tags--in the database.
    i had linked another php function and a brief discussion whence i noticed Rowsdower had pretty much covered it.
    didn't delete everything i guess...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Oh, of course. Makes sense. Of course, we don't even know if he is using PHP on server (or if he even has control of server). May never find out if he doesn't re-post.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    Yes, you always always (ALWAYS) do your data validation server-side, and generally do so before storing the data. You can mimic that same validation client-side to help legit users but the real teeth need to be server-side. Check your input against one or more character "whitelists" appropriate for your application before ever storing that data in the DB. (After all, why store "bad" data, right?) Then for your stored "clean" data, you still output that info with some form of htmlspecialchars or htmlentities, as appropriate for your needs. Personally, I lean on htmlspecialchars.

    I did over-simplify the htmlspecialchars part, though. You really have to be very careful to set all encoding to the same type (e.g. "UTF-8") in the DB connection, in the HTTP headers, in the HTML meta tags, and in the server-side script (in the htmlspecialchars function itself, as one of its parameters). As long as a consistent character encoding is used throughout your script and your DB, you can be relatively sure XSS won't slip through from user input (take a look into UTF-7 XSS exploits to see why this is important to set encoding in your script and in your pages served).

    IE6 is still a bit of a wildcard even after all of that, though. Luckily there isn't much IE6 madness to contend with these days.

    Intersting checklist for XSS protection in PHP:
    (ripped from http://blog.astrumfutura.com/2013/04...ipting-in-php/)
    Code:
    20 Point List For Preventing Cross-Site Scripting In PHP
    1. Never pass data from untrusted origins into output without either escaping or sanitising it.
    2. Never forget to validate data arriving from an untrusted origin using relevant rules for the context it’s used in.
    3. Remember that anything not explicitly defined in source code has an untrusted origin.
    4. Remember that htmlentities() is incompatible with XML, including HTML5′s XML serialisation – use htmlspecialchars().
    5. Always include ENT_QUOTES, ENT_SUBSTITUTE and a valid character encoding when calling htmlspecialchars().
    6. Never use htmlspecialchars() as the primary means of escaping Javascript, CSS or URL parts.
    7. Never use json_encode() to escape Javascript strings unless using PHP 5.3 and RTFM.
    8. Use rawurlencode() to escape strings being inserted into URLs and then HTML escape the entire URL.
    9. Never ever pass escaped or sanitised data from untrusted origins into a Javascript execution context: a string later executed as Javascript, e.g. setAttribute(“onclick”, “PLEASEGODNOTHERE”).
    10. Validate all complete URLs if constructed from untrusted data.
    11. Never validate URLs using filter_var(). It doesn’t work and allows Javascript and Data URIs through.
    12. Never include resources loaded over unsecured HTTP on a page loaded over HTTPS.
    13. Sanitise raw HTML from untrusted origins using HTMLPurifier before injecting it into ouput.
    14. Sanitise the output of Markdown, BBCode and other HTML replacements using HTMLPurifier before injecting it into output.
    15. Remember that HTMLPurifier is the only HTML sanitiser worth using.
    16. Adopt the Content Security Policy (CSP) header and abandon the use of inline CSS and Javascript where feasible.
    17. Always transmit, with content, a valid Content-Type header referencing a valid character encoding.
    18. Ensure that cookies for use solely by the server are marked HttpOnly.
    19. Ensure that cookies which must only be transmitted over HTTPS are marked Secure.
    20. Always review dependencies and other third party code for potential XSS vulnerabilities and vectors.

    Side note: mysql_real_escape_string() is only reliable for preventing SQL injection if you treat all of your data as strings in the query. Just make sure to put single quotes around all of your query values (so you use "SELECT * FROM table WHERE column='".$some_variable['key']."'" instead of "SELECT * FROM table WHERE column=".$some_variable['key']) and it will work well enough. Without that you can still be vulnerable to ASCII char values and hex values.
    Last edited by Rowsdower!; 05-30-2013 at 10:28 PM. Reason: Added a 20-point list reference...
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #8
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,462
    Thanks
    0
    Thanked 633 Times in 623 Posts
    If you use prepare and bind instead of query for your database calls then you will no longer need to escape the data as using the two calls instead of one keeps the data completely separate from the SQL and so makes injection completely impossiblew.

    Note also that all the mysql_ calls are about to be removed from PHP - you should be converting to use either the mysqli_ equivalents or PDO.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    I truly think that Rowsdower's "Side Note" is *BAD* advice.

    First of all, it only works if the DB in question is MySQL. Other database won't allow you to assign a string value to a numeric field. MySQL is incredibly *SLOPPY* which leads to the kind of ugly coding shown there.

    I strongly believe that you should, instead, ensure that the value in question *IS* numeric.

    In most languages, that's not an issue: You just make sure that you are using a numeric variable and you know it can't possibly hold some bogus string. In PHP and some other scripting-style languages, where a single variable might be a string or a number or a date or whatever, there are still many mechanisms you can use. For example, in PHP you might do:
    Code:
    if ( ! is_numeric( $some_variable['key'] ) /* check for a number */
    {
        echo "Invalid number for " . $some_variable['key'] . ", aborting.";
        exit( "Invalid data" );
    }
    $num = ( int ) $some_variable['key']; /* cast the string to a number to be sure */
    $sql = "SELECT * FROM table WHERE somIntField = $num ";
    ...
    Just because MySQL allows sloppiness doesn't mean you have to *BE* sloppy.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by felgall View Post
    Note also that all the mysql_ calls are about to be removed from PHP - you should be converting to use either the mysqli_ equivalents or PDO.
    Very true, but even with mysqli_ and PDO if you don't use prepared statements you need to sanitize your SQL commands.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #11
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    Quote Originally Posted by Old Pedant View Post
    I truly think that Rowsdower's "Side Note" is *BAD* advice.

    First of all, it only works if the DB in question is MySQL. Other database won't allow you to assign a string value to a numeric field. MySQL is incredibly *SLOPPY* which leads to the kind of ugly coding shown there.

    I strongly believe that you should, instead, ensure that the value in question *IS* numeric.

    In most languages, that's not an issue: You just make sure that you are using a numeric variable and you know it can't possibly hold some bogus string. In PHP and some other scripting-style languages, where a single variable might be a string or a number or a date or whatever, there are still many mechanisms you can use. For example, in PHP you might do:
    Code:
    if ( ! is_numeric( $some_variable['key'] ) /* check for a number */
    {
        echo "Invalid number for " . $some_variable['key'] . ", aborting.";
        exit( "Invalid data" );
    }
    $num = ( int ) $some_variable['key']; /* cast the string to a number to be sure */
    $sql = "SELECT * FROM table WHERE somIntField = $num ";
    ...
    Just because MySQL allows sloppiness doesn't mean you have to *BE* sloppy.
    I'd like to point out that I did not raise the idea of using mysql_real_escape_string anyway (I'm in mysqli these days and I know many are into PDO - in both cases this function is not relevant and you secure your query with proper binding). But if we're going to talk about using it I think we should mention its weakness and give the OP and others a way to solve the problem if they intend to use this function.

    I fully admit that the "stringification" of the query values is a MySQL hack. I tend to assume mysql functions are used for MySQL databases, though. I admit that I pretty much only use MySQL (I've also had to use odbc functions, but still to connect to a MySQL database), but I'm aware of there being PostgreSQL functions in PHP and that has painted my perception that different databases seem have different PHP functions to connect to them. If that is not a universal truth, then I stand corrected and note the exception.

    But I also firmly believe copy/paste coders (of the variety who, for example, copy/paste javascript with "document.write" all over it because they don't yet know the best way to achieve their goals) are more likely to add single quotes to their query than they are to properly check their variable types. Whether this is from a laziness on their part or from a lack of confidence that they'll do it properly, I think most of those novice coders will be more apt to use the hack, at least until they get better with their coding and realize 1) this is a hack, and 2) they shouldn't even be using PHP's deprecated mysql functions to begin with.

    Since we're seeing a question in the javascript section of the forum about preventing database-stored XSS code I'm assuming the OP is a novice at server-side/database stuff and will likely look to google and then blaze a glorious path of copy/paste coding to make a quick fix for their issue. So this side note was just meant to save a little heartache for the OP and other people who find this thread, lest they see the apparent endorsement of mysql_real_escape_string and get the notion that they can just run everything through that with no further thought and then dump it to the database and still be safe from all manner of SQL injection attempts. I know that is not what we intended, which is why I offered the side note. But perhaps a more lengthy explanation should have been put forth:

    I will amend my previous side note to say that validation/sanitization of database-bound data is NOT a 1-step process. But if you are going to try to 1-step it, the hack mentioned in my earlier post will keep you a little safer from SQL injection, provided you are using a MySQL database and PHP's deprecated mysql functions.

    The real and proper solution is to validate your data thoroughly, checking it for the expected data type and length (where its expected length can be roughly or precisely determined), whitelisting characters based on those expected values for strings (e.g. do people's "name" fields really need to allow slashes, hash marks, or most other non-alpha characters?), and then - if all of those earlier checks pass successfully - you set your database connection encoding to the same encoding you use in your pages and bind your parameters in the query which you should run through PDO or mysqli functions with the binding methods they offer. After that, when you want to display that data back to any users, always HTML-encode it on the way out and be sure to make your HTTP headers and meta tags all use an encoding type that matches the encoding type used when storing the data in the DB. And be careful of where you allow user-created input to be used. Inside of element attributes, for example, this can still open up XSS holes.

    The above approach is as good a method as I know of to secure your database application from SQL injection and XSS attacks.
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    See, now we agree. <grin/>

    Nice summarization.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    Quote Originally Posted by Old Pedant View Post
    See, now we agree. <grin/>

    Nice summarization.
    I think we've always agreed. I just didn't put up a big enough wall of text the first time around!

    Now if only we can get the OP to post in here again...
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #14
    New Coder
    Join Date
    Mar 2012
    Posts
    78
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi All,

    Thanks for all the comments, I will need to look into my stored files because I have to admit I think some are just plain javascript on pages where the source code can be read.

    The original reason for the post was that I heard of the situation where a 'package', as it were, was coded into a forms input field.

    My form to e-mail are PHP pages with some code to strip certain characters and as I said some forms that simply write information to a log on host which is not seen by anyone is in plain visible code on page, so I am going to see if I can add in a php part to do the strip which won't be visible in the code.

    Martin.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    I am going to see if I can add in a php part to do the strip which won't be visible in the code.
    Ummm...PHP is never "visible in the code" if by that you mean the coding is visible in the browser.

    Anyway, you can easily use a regular expression in PHP code to strip out all HTML tags.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •